问题
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