Skip to content

Commit

Permalink
♻️ refactor: 移除默认的 api key 配置,添加服务端校验逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
arvinxx committed Aug 28, 2023
1 parent dd5e8a2 commit 7713115
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 37 deletions.
3 changes: 3 additions & 0 deletions api/v1/_types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export interface Settings {
SERPAPI_API_KEY?: string;
}
16 changes: 9 additions & 7 deletions api/v1/_utils.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,30 @@
import { OrganicResults, Result } from '../../src/type';
import { Settings } from './_types';

const BASE_URL = 'https://serpapi.com/search';

const API_KEY = process.env.SERPAI_API_KEY;
const fetchResult = async (args: { query: string }, settings: Settings): Promise<Result> => {
const apiKey = settings.SERPAPI_API_KEY;

const { default: querystring } = await import('query-string');

const fetchResult = async ({ query: keywords }: { query: string }): Promise<Result> => {
const params = {
api_key: API_KEY,
api_key: apiKey,
engine: 'google',
gl: 'cn',
google_domain: 'google.com',
hl: 'zh-cn',
location: 'China',
q: keywords,
q: args.query,
};

const { default: querystring } = await import('query-string');

const query = querystring.stringify(params);

const res = await fetch(`${BASE_URL}?${query}`);

const data = await res.json();

if (data.error) throw data;

const results = data.organic_results as OrganicResults;

return results.map((r) => ({
Expand Down
26 changes: 22 additions & 4 deletions api/v1/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,33 @@
import {
PluginErrorType,
createErrorResponse,
getPluginSettingsStringFromRequest,
} from '@lobehub/chat-plugin-sdk';

import { Settings } from './_types';
import runner from './_utils';

export const config = {
runtime: 'edge',
};

export default async (req: Request) => {
if (req.method !== 'POST') return new Response('Method Not Allowed', { status: 405 });
if (req.method !== 'POST') return createErrorResponse(PluginErrorType.MethodNotAllowed);

const settings = getPluginSettingsStringFromRequest<Settings>(req);

if (!settings)
return createErrorResponse(PluginErrorType.PluginSettingsInvalid, {
message: 'Plugin settings not found.',
});

const args = await req.json();
try {
const args = await req.json();

const result = await runner(args);
const result = await runner(args, settings);

return new Response(JSON.stringify(result));
return new Response(JSON.stringify(result));
} catch (error) {
return createErrorResponse(PluginErrorType.PluginServerError, error as object);
}
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"prepublishOnly": "npm run doctor && npm run build",
"prettier": "prettier -c --write \"api/**/*\"",
"release": "semantic-release",
"start": "vercel dev",
"start": "vercel dev --listen 3400",
"test": "vitest --passWithNoTests",
"test:coverage": "vitest --coverage --passWithNoTests",
"type-check": "tsc --noEmit"
Expand Down
30 changes: 5 additions & 25 deletions src/Render.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
import { PluginRenderProps } from '@lobehub/chat-plugin-sdk';
import { Icon } from '@lobehub/ui';
import { Segmented } from 'antd';
import { createStyles } from 'antd-style';
import { LucideLayoutGrid, LucideList } from 'lucide-react';
import { memo, useState } from 'react';
import { memo } from 'react';
import { Flexbox } from 'react-layout-kit';

import GridItem from './GridItem';
import ListItem from './ListItem';
import { Result } from './type';

const useStyles = createStyles(({ css }) => {
Expand All @@ -26,29 +22,13 @@ const useStyles = createStyles(({ css }) => {

const Render = memo<PluginRenderProps<Result>>(({ content }) => {
const { styles, cx } = useStyles();
const [mode, setMode] = useState('grid');

const isGrid = mode === 'grid';
return (
<Flexbox gap={8}>
<Flexbox align={'center'} horizontal justify={'space-between'}>
<Flexbox>Search Results:{content.length}</Flexbox>
<Flexbox>
<Segmented
onChange={(v) => setMode(v as any)}
options={[
{ icon: <Icon icon={LucideLayoutGrid} />, value: 'grid' },
{ icon: <Icon icon={LucideList} />, value: 'list' },
]}
size={'small'}
value={mode}
/>
</Flexbox>
</Flexbox>
<div className={cx(styles.container, isGrid && styles.grid)}>
{content.map((item) =>
isGrid ? <GridItem {...item} key={item.link} /> : <ListItem {...item} key={item.link} />,
)}
<div className={cx(styles.container, styles.grid)}>
{content.map((item) => (
<GridItem {...item} key={item.link} />
))}
</div>
</Flexbox>
);
Expand Down
1 change: 1 addition & 0 deletions src/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export interface SearchItem {
source?: string;
title: string;
}

export type Result = SearchItem[];

interface OrganicResult {
Expand Down

0 comments on commit 7713115

Please sign in to comment.