Skip to content

Commit

Permalink
feat: 完成接口开发
Browse files Browse the repository at this point in the history
  • Loading branch information
crazyurus committed Aug 17, 2024
1 parent 7277b85 commit 29793ca
Show file tree
Hide file tree
Showing 8 changed files with 162 additions and 17 deletions.
7 changes: 5 additions & 2 deletions api/app.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import Koa, { Context } from 'koa';
import koaBody from 'koa-body';
import body from 'koa-body';
import logger from 'koa-logger';

const app = new Koa();

app.use(async (ctx: Context, next) => {
console.info(`access url: ${ctx.url}`);
await next();
});

app.use(koaBody());
app.use(body());
app.use(logger());

export default app;
7 changes: 0 additions & 7 deletions api/lambda/hello.ts

This file was deleted.

52 changes: 52 additions & 0 deletions api/lambda/translate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */
/* eslint-disable node/prefer-global/text-decoder */
import type { RequestOption } from '@modern-js/runtime/server';

export async function post(context: RequestOption<never, { text: string }>) {
const { text } = context.data;

const response = await fetch('https://api.coze.cn/v3/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.COZE_API_KEY}`,
},
body: JSON.stringify({
bot_id: '7400050699922767910',
user_id: 'anonymous',
auto_save_history: false,
stream: true,
additional_messages: [
{
role: 'user',
content: text,
content_type: 'text',
},
],
}),
});
const reader = response.body?.getReader()!;
let result = '';

while (true) {
const { value, done } = await reader.read();
const textDecoder = new TextDecoder();
const chunk = textDecoder.decode(value);
const lines = chunk.split('\n');
const event = lines[0];

if (event === 'event:conversation.message.completed' || done) {
break;
}

if (event === 'event:conversation.message.delta') {
const json = JSON.parse(lines[1].slice(5));

result += json.content;
}
}

return {
result: result.trim(),
};
}
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,12 @@
"@douyinfe/semi-ui": "^2.64.0",
"@modern-js/plugin-bff": "^2.58.1",
"@modern-js/plugin-koa": "^2.58.1",
"@modern-js/plugin-polyfill": "2.58.1",
"@modern-js/plugin-tailwindcss": "2.58.1",
"@modern-js/plugin-polyfill": "^2.58.1",
"@modern-js/plugin-tailwindcss": "^2.58.1",
"@modern-js/runtime": "^2.58.1",
"koa": "^2.15.3",
"koa-body": "^6.0.1",
"koa-logger": "^3.2.1",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
Expand All @@ -44,6 +45,7 @@
"@modern-js/tsconfig": "^2.58.1",
"@types/jest": "^29.5.12",
"@types/koa": "^2.15.0",
"@types/koa-logger": "^3.1.5",
"@types/node": "^22.4.0",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
Expand Down
38 changes: 36 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 24 additions & 0 deletions src/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { useState, useCallback } from 'react';

export function useLoading<F extends (...args: any) => Promise<any>>(
handler: F,
): [F, boolean, Error | undefined] {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error>();
const newHandler = useCallback(
(...args: any) => {
setLoading(true);

return handler(...args)
.catch(e => {
setError(e);
})
.finally(() => {
setLoading(false);
});
},
[handler],
);

return [newHandler as F, loading, error];
}
4 changes: 4 additions & 0 deletions src/routes/page.module.scss
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
.container {
padding: 24px 60px;

:global(.semi-input-textarea-readonly) {
color: var(--semi-color-text-0);
}
}

.title {
Expand Down
41 changes: 37 additions & 4 deletions src/routes/page.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,36 @@
import { useState } from 'react';
import { Button, TextArea } from '@douyinfe/semi-ui';
import { Button, TextArea, Toast } from '@douyinfe/semi-ui';

import { post as translate } from '@api/translate';
import { useLoading } from '../hooks';

import styles from './page.module.scss';

function IndexPage(): JSX.Element {
const [text, setText] = useState('');
const [result, setResult] = useState('');

const [handleTranslate, loading] = useLoading(async () => {
const { result } = await translate({
data: {
text,
},
});

setResult(result);
});

const handleCopy = async () => {
await navigator.clipboard.writeText(result);

Toast.success('Copied');
};

const handleReset = () => {
setText('');
setResult('');
};

return (
<div className={styles.container}>
<div className={styles.title}>English</div>
Expand All @@ -25,9 +49,18 @@ function IndexPage(): JSX.Element {
onChange={setResult}
/>
<div className={styles.footer}>
<Button theme="solid">Translate</Button>
<Button>Copy</Button>
<Button>Reset</Button>
<Button
loading={loading}
disabled={!text}
theme="solid"
onClick={handleTranslate}
>
Translate
</Button>
<Button disabled={!result} onClick={handleCopy}>
Copy
</Button>
<Button onClick={handleReset}>Reset</Button>
</div>
</div>
);
Expand Down

0 comments on commit 29793ca

Please sign in to comment.