egg-oauth2-server icon indicating copy to clipboard operation
egg-oauth2-server copied to clipboard

Saving context in application is an anti-pattern

Open geekdada opened this issue 7 years ago • 5 comments

I found on some occasions, the Model being instantiated with the last request context, then I found this:

https://github.com/Azard/egg-oauth2-server/blob/2d10b76142080b60e8fc3e0742cea25e5788111a/lib/server.js#L86

You should never save ctx in application ever. This is my fix:

{
  getServer(ctx) {
    if (!ctx[SERVER]) {
      const { config, model: Model } = this;
      const model = new Model(ctx);
      ctx[SERVER] = new AuthServer(Object.assign(config, { model }));
      return ctx[SERVER];
    }
    return ctx[SERVER];
  }
}

geekdada avatar Nov 27 '18 08:11 geekdada

Or probably, use app/extend/context.js to get AuthServer attached on ctx.

geekdada avatar Nov 27 '18 08:11 geekdada

ctx[SERVER] = new AuthServer(Object.assign(config, { model })); could create AuthServer every time, it's not performance.

Azard avatar Nov 28 '18 17:11 Azard

I'm a little confused, then what's this for?

https://github.com/Azard/egg-oauth2-server/blob/2d10b76142080b60e8fc3e0742cea25e5788111a/lib/server.js#L77

If creating a new instance every time when a request comes is a bad approach, maybe you shouldn't have made Model has ctx as parameters in the first place.

geekdada avatar Nov 29 '18 01:11 geekdada

I found this PR https://github.com/oauthjs/node-oauth2-server/pull/462

geekdada avatar Nov 29 '18 02:11 geekdada

Has the problem been solved?

rise0chen avatar Jun 19 '19 04:06 rise0chen