Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: make Context state property can be override by Sub Class #14

Merged
merged 1 commit into from
Dec 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions example/extend/Context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Context } from '../../src/index.js';

export class CustomContext extends Context {
get state() {
return { foo: 'bar' };
}
}
7 changes: 5 additions & 2 deletions src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,14 @@ export class Context {
res: ServerResponse;
request: Request & AnyProto;
response: Response & AnyProto;
state: Record<string, any>;
originalUrl: string;
respond?: boolean;
#state: Record<string, any> = {};

constructor(app: Application, req: IncomingMessage, res: ServerResponse) {
this.app = app;
this.req = req;
this.res = res;
this.state = {};
this.request = new app.RequestClass(app, this, req, res);
this.response = new app.ResponseClass(app, this as any, req, res);
this.request.response = this.response;
Expand Down Expand Up @@ -219,6 +218,10 @@ export class Context {
set cookies(cookies: Cookies) {
this._cookies = cookies;
}

get state() {
return this.#state;
}
}

/**
Expand Down
6 changes: 5 additions & 1 deletion src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ import type { Application } from './application.js';
import type { ContextDelegation } from './context.js';
import type { Response } from './response.js';

export interface RequestSocket extends Socket {
encrypted: boolean;
}

export class Request {
[key: symbol]: unknown;
app: Application;
Expand Down Expand Up @@ -299,7 +303,7 @@ export class Request {
* Return the request socket.
*/
get socket() {
return this.req.socket as (Socket & { encrypted: boolean; });
return this.req.socket as RequestSocket;
}

/**
Expand Down
11 changes: 11 additions & 0 deletions test/application/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,15 @@ describe('app', () => {
throw CreateError(500, 'test error');
}, Koa.HttpError);
});

it('should print object work', () => {
const app = new Koa();
const ctx = (app as any).createContext({} as any, {
getHeaders() {},
} as any);
console.log(ctx.request);
console.log(ctx.response);
console.log(ctx.context);
console.log(app);
});
fengmk2 marked this conversation as resolved.
Show resolved Hide resolved
});
29 changes: 29 additions & 0 deletions test/context/state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,35 @@ describe('ctx.state', () => {

app.use(ctx => {
assert.deepStrictEqual(ctx.state, {});
ctx.state.user = 'example';
});

app.use(ctx => {
assert.deepStrictEqual(ctx.state, { user: 'example' });
});

const server = app.listen();

return request(server)
.get('/')
.expect(404);
});
Comment on lines +18 to +23
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add server cleanup after test completion.

The server should be closed after the test completes to prevent resource leaks:

   const server = app.listen();

   return request(server)
     .get('/')
-    .expect(404);
+    .expect(404)
+    .then(() => server.close());
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const server = app.listen();
return request(server)
.get('/')
.expect(404);
});
const server = app.listen();
return request(server)
.get('/')
.expect(404)
.then(() => server.close());
});


it('should override state getter', () => {
const app = new Koa();
app.ContextClass = class extends app.ContextClass {
get state(): Record<string, string> {
return { foo: 'bar' };
}
};

app.use(ctx => {
assert.deepStrictEqual(ctx.state, { foo: 'bar' });
(ctx.state as any).user = 'example';
});

app.use(ctx => {
assert.deepStrictEqual(ctx.state, { foo: 'bar' });
});

const server = app.listen();
Expand Down
Loading