【问题标题】:Access model method inside express route (Loopback 4)快速路由内的访问模型方法(Loopback 4)
【发布时间】:2021-02-11 02:37:25
【问题描述】:

我将向您展示我正在尝试做的一个示例:

server.ts

export class ExpressServer {
  public readonly app: express.Application;
  public readonly lbApp: ImportedApp;
  private server?: Server;

  constructor(options: ApplicationConfig = {}) {
    this.app = express();
    this.lbApp = new ImportedApp(options);
    this.app.get('/hello', async function (_req: Request, res: Response) {
      //Here i'd like to call a model like User.findById() but can't figure out how to do it..
    });

  }
}

正如您在评论中看到的那样,我正在尝试访问我的模型方法以在我的路线中使用它们(比如在我的视图中显示用户信息)但无法弄清楚如何去做。我已经尝试导入数据源、模型、控制器,但没有包含我的方法(FindById、Create 等)

如果我什么也没找到,我将不得不使用 AxiosRequest 之类的东西从 api 请求资源,而不是像 await request('api/users/myusername) 这样在我的代码中请求资源

【问题讨论】:

    标签: node.js typescript express loopbackjs loopback4


    【解决方案1】:

    在 LoopBack 4 中,我们使用存储库设计模式来访问数据。为了通过 id 找到用户实例,您需要通过依赖注入获取UserRepository 的实例。引用https://loopback.io/doc/en/lb4/Repository.html:

    存储库正在向模型添加行为。模型描述数据的形状,存储库提供类似 CRUD 操作的行为。这与模型也实现行为的 LoopBack 3.x 不同。

    更新的解决方案

    要获取 Repository 类的实例,您可以使用 Service Locator 设计模式并从 LoopBack 的 REST 层提供的 per-request Context 对象中获取实例。

    import {MIDDLEWARE_CONTEXT, RequestContext} from '@loopback/rest';
    import {UserRepository} from '../repositories';
    
    function expressHandler(req, res, next) {
      const ctx = (req as any)[MIDDLEWARE_CONTEXT];  
      const userRepo = await ctx.get<UserRepository>('repositories.UserRepository');
      const users = await userRepo.find({limit: 10});
      // render your view
    }
    

    我们正在讨论如何在 GitHub 拉取请求 loopback-next#6793 中更轻松地实现此用例,欢迎随时加入讨论。

    原始答案

    我建议您编写一个 LoopBack 4 控制器,而不是为您呈现的页面编写 Express 路由;并注入 Express Response 对象以允许您呈现 HTML 视图,如 https://loopback.io/doc/en/lb4/Accessing-http-request-response.html#inject-http-response 中所述

    import {Response, RestBindings, oas} from '@loopback/rest';
    import {inject} from '@loopback/core';
    import {UserRepository} from '../repositories';
    
    export class PingController {
      constructor(
        @inject(RestBindings.Http.RESPONSE) 
        private response: Response
    
        @repository(UserRepository)
        public userRepository: UserRepository,
      ) {}
    
      // Hide this endpoint from OpenAPI spec generated for the app
      @oas.visibility('undocumented')
      @get('/users')
      list(): Response {
        // Access User data via this.userRepository API
        const users = await this.userRepository.find({limit: 10});
    
        // Access the response object via `this.response`
        this.response.render('users', {users});
    
        // Return the HTTP response object so that LoopBack framework skips the
        // generation of HTTP response
        return this.response;
      }
    }
    

    话虽如此,如果您已经知道如何在 Express 路由中从 LB4 应用程序访问 DataSource 实例,那么您也可以从路由中手动实例化 Repository 类:

    const db = // your datasource
    
    this.app.get('/hello', async function (_req: Request, res: Response) {
      const repo = new UserRepository(db);
      const users = await this.userRepository.find({limit: 10});
    });
    

    【讨论】:

      【解决方案2】:

      对我来说,解决方案不起作用。从 express-composition 示例开始,我只需要从 lb4 请求处理程序的通用快速路由 outside 访问 lb 存储库:

      constructor(options: ApplicationConfig = {}) {
        this.app = express();
        this.lbApp = new NoteApplication(options);
        this.lbApp.basePath('')
      
        // Expose the front-end assets via Express, not as LB4 route
        this.app.use('/api', this.lbApp.requestHandler);
      
        this.app.get('/hello', async (req: Request, res: Response) => {
          const ctx = (req as any)[MIDDLEWARE_CONTEXT];
          const userRepo = await ctx.get('repositories.UserRepository');
          res.send('Hello world!');
        });
      }
      

      行中的ctx

      const ctx = (req as any)[MIDDLEWARE_CONTEXT];
      

      总是未定义的。

      我的主要目标是让路由不在 /api 下仍然可以访问 lb4 存储库。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多