Skip to content

Commit

Permalink
fix: fix error when request has no body pass
Browse files Browse the repository at this point in the history
Signed-off-by: seven <zilisheng1996@gmail.com>
  • Loading branch information
Blankll committed Dec 21, 2024
1 parent 7125a7a commit f7d5c00
Show file tree
Hide file tree
Showing 7 changed files with 142 additions and 100 deletions.
64 changes: 34 additions & 30 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@geek-fun/serverless-adapter",
"version": "0.0.1",
"version": "0.0.2",
"description": "Adapter for web frame work express, koa, springboot to run in serverless function as backend of apigateway cross multi cloud provider like aliyun, huawei",
"homepage": "https://www.geekfun.club/",
"main": "dist/src/index.js",
Expand Down
14 changes: 12 additions & 2 deletions src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,22 @@ import url from 'node:url';
import ServerlessResponse from './serverlessResponse';
import { debug } from './common';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
// const requestRemoteAddress = (event) => {
// if (event.version === '2.0') {
// return event.requestContext.http.sourceIp;
// }
// return event.requestContext.identity.sourceIp;
// };

export const constructFrameworkContext = (event: Event, context: Context) => {
debug(`constructFrameworkContext: ${JSON.stringify({ event, context })}`);
const request = new ServerlessRequest({
method: event.httpMethod,
headers: event.headers,
body: Buffer.from(event.body, event.isBase64Encoded ? 'base64' : 'utf8'),
body:
event.body !== undefined && event.body !== null
? Buffer.from(event.body, event.isBase64Encoded ? 'base64' : 'utf8')
: undefined,
remoteAddress: '',
url: url.format({
pathname: event.path,
Expand All @@ -19,5 +28,6 @@ export const constructFrameworkContext = (event: Event, context: Context) => {
isBase64Encoded: event.isBase64Encoded,
});
const response = new ServerlessResponse(request);

return { request, response };
};
6 changes: 3 additions & 3 deletions src/serverlessRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ interface ServerlessRequestOptions {
method: string;
url: string;
headers: { [key: string]: string | number };
body: Buffer | string;
body: Buffer | string | undefined;
remoteAddress: string;
isBase64Encoded: boolean;
}
Expand All @@ -17,7 +17,7 @@ const NO_OP: (...args: unknown[]) => unknown = () => void 0;
export default class ServerlessRequest extends IncomingMessage {
ip: string;

body: Buffer | string;
body: Buffer | string | undefined;

isBase64Encoded: boolean;

Expand All @@ -41,7 +41,7 @@ export default class ServerlessRequest extends IncomingMessage {
const combinedHeaders = Object.fromEntries(
Object.entries({
...headers,
'content-length': Buffer.byteLength(body).toString(),
'content-length': Buffer.byteLength(body ?? '').toString(),
}).map(([key, value]) => [key.toLowerCase(), value]),
);

Expand Down
10 changes: 6 additions & 4 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ type AliyunApiGatewayEvent = {
headers: Record<string, string>;
queryParameters: Record<string, string>;
pathParameters: Record<string, string>;
body: string;
body?: string;
isBase64Encoded: boolean;
};

type AliyunApiGatewayContext = {
requestId: string;
region: string;
accountId: string;
credentials: {
accessKeyId: string;
accessKeySecret: string;
Expand All @@ -29,9 +31,9 @@ type AliyunApiGatewayContext = {
name: string;
logProject: string;
logStore: string;
qualifier: string;
versionId: string;
};
region: string;
accountId: string;
tracing: {
spanContext: string;
jaegerEndpoint: string;
Expand All @@ -48,8 +50,8 @@ type AliyunApiGatewayContext = {
};

export type Event = AliyunApiGatewayEvent;

export type Context = AliyunApiGatewayContext;

export type ServerlessAdapter = (app: Express) => (
event: Event,
context: Context,
Expand Down
62 changes: 62 additions & 0 deletions tests/fixtures/fcContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { Context, Event } from '../../src/types';

export const defaultEvent: Event = {
path: '/api/test',
httpMethod: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer sampleToken',
},
queryParameters: {
param1: 'value1',
param2: 'value2',
},
pathParameters: {
id: '123',
},
body: '{"key":"value"}',
isBase64Encoded: false,
};
export const defaultContext: Context = {
requestId: 'sample-request-id',
credentials: {
accessKeyId: 'sample-access-key-id',
accessKeySecret: 'sample-access-key-secret',
securityToken: 'sample-security-token',
},
function: {
name: 'sample-function-name',
handler: 'sample-function-handler',
memory: 128,
timeout: 30,
initializer: 'sample-initializer',
},
service: {
name: 'sample-service-name',
logProject: 'sample-log-project',
logStore: 'sample-log-store',
qualifier: 'sample-qualifier',
versionId: 'sample-version-id',
},
region: 'sample-region',
accountId: 'sample-account-id',
tracing: {
spanContext: 'sample-span-context',
jaegerEndpoint: 'sample-jaeger-endpoint',
spanBaggages: {
baggage1: 'value1',
baggage2: 'value2',
},
parseOpenTracingBaggages: () => ({
baggage1: 'value1',
baggage2: 'value2',
}),
},
logger: {
debug: (message: string) => console.debug(message),
info: (message: string) => console.info(message),
warn: (message: string) => console.warn(message),
error: (message: string) => console.error(message),
log: (message: string) => console.log(message),
},
};
Loading

0 comments on commit f7d5c00

Please sign in to comment.