-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
84 lines (75 loc) · 2.52 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { APIGatewayProxyResult, APIGatewayEvent } from 'aws-lambda';
import CustomError from '@/customError/CustomErrorClass';
import { matchNameViaAi } from '@/handlers/aiHandler';
import { NAME_LIST } from '@/constant/nameList';
import { isChineseOnly, isEnglishOnly, splitName } from '@/utils';
import { matchNameManually } from '@/handlers/manualHandler';
/**
* Handler function that processes the API Gateway event validates the input name,and returns the best match name,
* matches the name either via AI or manually, and returns the result in a JSON format.
*
* @param {APIGatewayEvent} event - The API Gateway event object containing the request details.
* @return {Promise<APIGatewayProxyResult>} A promise that resolves to an API Gateway proxy result.
*/
export const handler = async (event: APIGatewayEvent): Promise<APIGatewayProxyResult> => {
try {
const { name = '', isManual = '' } = event.queryStringParameters || {};
const trimmedName = name.trim();
if (!trimmedName || typeof trimmedName !== 'string' || trimmedName.trim().length === 0) {
// Invalid empty input name
throw new CustomError(
'Invalid input name, The input name must be a string and cannot be empty.',
400,
);
}
const splitedInputName = splitName(trimmedName);
for (const name of splitedInputName) {
if (!isChineseOnly(name) && !isEnglishOnly(name)) {
// Invalid input name
throw new CustomError(
'Invalid input name. The input name can only consist of Chinese and English characters, along with spaces; numbers, symbols, or other characters are not allowed.',
400,
);
}
}
let result = {};
let type = 'AI';
if (isManual === 'true') {
// Manual match mode by codes
type = 'manual';
result = matchNameManually(trimmedName, NAME_LIST);
} else {
// AI match mode
result = await matchNameViaAi(trimmedName);
}
return {
statusCode: 200,
body: JSON.stringify({
type,
input: name,
data: {
...result,
},
}),
};
} catch (error: unknown) {
let message = '';
let code = 500;
if (error instanceof CustomError) {
message = error.message;
code = error.code;
} else {
message = 'Unknown error';
}
return {
statusCode: code,
body: JSON.stringify({
input: event?.queryStringParameters?.name || '',
data: {
bestMatchName: '',
message,
},
}),
};
}
};