Skip to content

Commit

Permalink
feat: route handlers to use 'call' method for binding 'this'
Browse files Browse the repository at this point in the history
  • Loading branch information
alimd committed Sep 14, 2024
1 parent 1aabff4 commit 69517c1
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
6 changes: 3 additions & 3 deletions packages/api-server/src/api-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,14 +260,14 @@ export class NanotronApiServer {
try {
for (const handler of routeOption.preHandlers) {
if (connection.terminatedHandlers === true) return;
await handler(connection, connection.serverResponse, connection.sharedMeta);
await handler.call(connection, connection, connection.serverResponse, connection.sharedMeta);
}

await routeOption.handler(connection, connection.serverResponse, connection.sharedMeta);
await routeOption.handler.call(connection, connection, connection.serverResponse, connection.sharedMeta);

for (const handler of routeOption.postHandlers) {
if (connection.terminatedHandlers === true) return;
await handler(connection, connection.serverResponse, connection.sharedMeta);
await handler.call(connection, connection, connection.serverResponse, connection.sharedMeta);
}
}
catch (error) {
Expand Down
1 change: 1 addition & 0 deletions packages/api-server/src/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export type ErrorResponse = {
};

export type RouteHandler<TSharedMeta extends Dictionary = Dictionary> = (
this: NanotronClientRequest<TSharedMeta>,
clientRequest: NanotronClientRequest<TSharedMeta>,
serverResponse: NanotronServerResponse,
sharedMeta: TSharedMeta,
Expand Down
17 changes: 14 additions & 3 deletions packages/nanotron/demo/api-server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,23 @@ apiServer.defineRoute({
}
});

apiServer.defineRoute({
method: 'GET',
url: '/hello3',
handler () {
this.serverResponse.replyJson({
ok: true,
message: 'Hello :)',
});
}
});

apiServer.defineRoute({
method: 'POST',
url: '/echo-body',
async handler (connection) {
const body = await connection.getBodyRaw();
connection.serverResponse.replyJson({
async handler () {
const body = await this.getBodyRaw();
this.serverResponse.replyJson({
ok: true,
data: body.toString(),
});
Expand Down

0 comments on commit 69517c1

Please sign in to comment.