2021-08-09 18:05:01 +08:00
|
|
|
// cfc 入口。
|
|
|
|
exports.handler = (event, context, callback) => {
|
|
|
|
try {
|
|
|
|
const entry = require('./mock/index');
|
|
|
|
entry(mockRequest(event, context), mockResponse(event, context, callback));
|
|
|
|
} catch (e) {
|
|
|
|
callback(e.stack);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
function mockRequest(event, context) {
|
|
|
|
let body = {};
|
|
|
|
|
|
|
|
if (
|
|
|
|
event.body &&
|
|
|
|
typeof event.body === 'string' &&
|
|
|
|
/^application\/json/i.test(event.headers['Content-Type'])
|
|
|
|
) {
|
|
|
|
body = JSON.parse(event.body);
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
query: event.queryStringParameters || {},
|
|
|
|
method: 'GET',
|
|
|
|
body: body,
|
|
|
|
url: `/api/${event.pathParameters.subpath}`,
|
2021-11-25 16:35:38 +08:00
|
|
|
originalUrl: ''
|
2021-08-09 18:05:01 +08:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
function mockResponse(event, context, callback) {
|
|
|
|
return {
|
|
|
|
json(json) {
|
|
|
|
callback(null, {
|
|
|
|
statusCode: 200,
|
|
|
|
headers: createHeaders(event.headers),
|
2021-11-25 16:35:38 +08:00
|
|
|
body: JSON.stringify(json)
|
2021-08-09 18:05:01 +08:00
|
|
|
});
|
|
|
|
},
|
2022-07-29 18:10:07 +08:00
|
|
|
send(res, headers = {}) {
|
2021-11-25 16:35:38 +08:00
|
|
|
callback(null, {
|
|
|
|
statusCode: 200,
|
|
|
|
headers: {
|
|
|
|
...createHeaders(event.headers),
|
2022-07-29 18:10:07 +08:00
|
|
|
'Content-Type': 'text/javascript',
|
|
|
|
...headers
|
2021-11-25 16:35:38 +08:00
|
|
|
},
|
|
|
|
json: false,
|
|
|
|
body: res
|
|
|
|
});
|
|
|
|
}
|
2021-08-09 18:05:01 +08:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
function createHeaders(headers) {
|
|
|
|
let referer = '';
|
|
|
|
|
2022-04-25 16:45:39 +08:00
|
|
|
if (/^(https?\:\/\/[^:\/]+(?:\:\d+)?\/)/i.test(headers['referer'])) {
|
2021-08-09 18:05:01 +08:00
|
|
|
referer = RegExp.$1.replace(/\/$/, '');
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
'Content-Type': 'Application/json',
|
|
|
|
'Access-Control-Allow-Headers': 'x-requested-with,content-type',
|
|
|
|
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS,HEAD',
|
|
|
|
'Access-Control-Allow-Credentials': 'true',
|
2021-11-25 16:35:38 +08:00
|
|
|
'Access-Control-Allow-Origin': referer ? `${referer}` : '*'
|
2021-08-09 18:05:01 +08:00
|
|
|
};
|
|
|
|
}
|