How to use stateful requests in Loopback 4?

自作多情 提交于 2020-05-13 18:11:08

问题


In v3, we could define middlewares on underlying Express, such as express-session, to add a session property on requests objects.

In v4, it looks like there is no equivalent for this, and the underlying Express is not exposed.

I am migrating an authentication provider from v3 to v4 and I'm stuck because of that. How can I do?

I tried the following workaround but it didn't work:

import { MyApplication } from './application';
import { ApplicationConfig } from '@loopback/core';

const expressSession = require('express-session');

export { MyApplication };

export async function main(options: ApplicationConfig = {}) {
  const app = new MyApplication (options);
  // @ts-ignore
  app.restServer._expressApp.use(expressSession);
  await app.boot();
  await app.start();

  const url = app.restServer.url;
  console.log(`Server is running at ${url}`);
  console.log(`Try ${url}/ping`);

  return app;
}

回答1:


Hello from the LoopBack team :)

We haven't looked into supporting HTTP sessions and stateful requests yet. Ideally, session handling should be implemented as a new Sequence action - see Sequence docs.

class MySequence {
  // skipping constructor with dependencies to be injected

  async handle(context: RequestContext) {
    try {
      // the following line is new
      const session = this.restoreSession(context);

      // the default sequence continues here
      const route = this.findRoute(context.request);
      const params = await this.parseParams(context.request, route);
      const result = await this.invoke(route, params);
      await this.send(context.response, result);
    } catch (error) {
      await this.reject(context, error);
    }
  }
}

The sequence action restoreSession should:

  • check if there are any session cookies present in the request
  • load the session if a cookie was provided, maybe create a new one otherwise?
  • bind the session in our Context so that other places like controllers can receive the session via Dependency Injection

Could you please open a new GitHub issue (a feature request) in loopback-next so that we can discuss implementation specifics there?



来源:https://stackoverflow.com/questions/52833380/how-to-use-stateful-requests-in-loopback-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!