我正在关注文档here,我想在环回中编写一个中间件来记录所有请求。 我写了这个中间件提供程序:
@injectable(
asMiddleware({
group: 'log',
upstreamGroups: ['sendResponse'],
chain: RestTags.REST_MIDDLEWARE_CHAIN,
}),
)
export class LogMiddlewareProvider
implements Provider<Middleware> {
value(): Middleware {
return async (ctx, next) => {
const {request} = ctx
try {
console.log(request.method);
const result = await next();
return result;
} catch (err) {
console.log(err);
throw err;
}
}
}
}
但是我在文档中找不到如何使用此提供程序以及如何将其注入序列或我的应用程序中
您可以通过导入将其注册到
application.ts
中,然后在构造函数中将其注册到应用程序中。
这是例子
....
import { LogMiddlewareProvider } from './middleware/another.middleware';
export class SampleAppApplication extends BootMixin(
ServiceMixin(RepositoryMixin(RestApplication)),
) {
constructor(options: ApplicationConfig = {}) {
super(options);
// the middleware is being registered here,
this.middleware(LogMiddlewareProvider);
// Set up the custom sequence
this.sequence(MySequence);
// Set up default home page
this.static('/', path.join(__dirname, '../public'));
// Customize @loopback/rest-explorer configuration here
this.configure(RestExplorerBindings.COMPONENT).to({
path: '/explorer',
});
this.component(RestExplorerComponent);
this.projectRoot = __dirname;
// Customize @loopback/boot Booter Conventions here
this.bootOptions = {
controllers: {
// Customize ControllerBooter Conventions here
dirs: ['controllers'],
extensions: ['.controller.js'],
nested: true,
},
};
this.component(CrudRestComponent);
}
}