v4.5 (#403)
This commit is contained in:
19
packages/common/tools/nextjs.ts
Normal file
19
packages/common/tools/nextjs.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { NextApiResponse, NextApiHandler, NextApiRequest } from 'next';
|
||||
import NextCors from 'nextjs-cors';
|
||||
|
||||
export function withNextCors(handler: NextApiHandler): NextApiHandler {
|
||||
return async function nextApiHandlerWrappedWithNextCors(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) {
|
||||
const methods = ['GET', 'eHEAD', 'PUT', 'PATCH', 'POST', 'DELETE'];
|
||||
const origin = req.headers.origin;
|
||||
await NextCors(req, res, {
|
||||
methods,
|
||||
origin: origin,
|
||||
optionsSuccessStatus: 200
|
||||
});
|
||||
|
||||
return handler(req, res);
|
||||
};
|
||||
}
|
||||
@@ -13,20 +13,10 @@ export const hashStr = (psw: string) => {
|
||||
/* simple text, remove chinese space and extra \n */
|
||||
export const simpleText = (text: string) => {
|
||||
text = text.replace(/([\u4e00-\u9fa5])[\s&&[^\n]]+([\u4e00-\u9fa5])/g, '$1$2');
|
||||
text = text.replace(/\n{2,}/g, '\n');
|
||||
text = text.replace(/\n{3,}/g, '\n\n');
|
||||
text = text.replace(/[\s&&[^\n]]{2,}/g, ' ');
|
||||
text = text.replace(/[\x00-\x08]/g, ' ');
|
||||
text = text.replace(/\r\n|\r/g, '\n');
|
||||
|
||||
// replace empty \n
|
||||
let newText = '';
|
||||
let lastChar = '';
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const currentChar = text[i];
|
||||
if (currentChar === '\n' && !/[。?!;.?!;]/g.test(lastChar)) {
|
||||
} else {
|
||||
newText += currentChar;
|
||||
}
|
||||
lastChar = currentChar;
|
||||
}
|
||||
return newText;
|
||||
return text;
|
||||
};
|
||||
|
||||
39
packages/common/tools/stream.ts
Normal file
39
packages/common/tools/stream.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import type { NextApiResponse } from 'next';
|
||||
|
||||
export function responseWriteController({
|
||||
res,
|
||||
readStream
|
||||
}: {
|
||||
res: NextApiResponse;
|
||||
readStream: any;
|
||||
}) {
|
||||
res.on('drain', () => {
|
||||
readStream.resume();
|
||||
});
|
||||
|
||||
return (text: string | Buffer) => {
|
||||
const writeResult = res.write(text);
|
||||
if (!writeResult) {
|
||||
readStream.pause();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function responseWrite({
|
||||
res,
|
||||
write,
|
||||
event,
|
||||
data
|
||||
}: {
|
||||
res?: NextApiResponse;
|
||||
write?: (text: string) => void;
|
||||
event?: string;
|
||||
data: string;
|
||||
}) {
|
||||
const Write = write || res?.write;
|
||||
|
||||
if (!Write) return;
|
||||
|
||||
event && Write(`event: ${event}\n`);
|
||||
Write(`data: ${data}\n\n`);
|
||||
}
|
||||
Reference in New Issue
Block a user