Access model method inside express route (Loopback 4)

In LoopBack 4, we use Repository design patter for accessing data. In order to find a user instance by its id, you need to obtain an instance of UserRepository via dependency injection. Quoting from

Repositories are adding behavior to Models. Models describe the shape of data, Repositories provide behavior like CRUD operations. This is different from LoopBack 3.x where models implement behavior too.


To obtain an instance of a Repository class, you can use the Service Locator design pattern and get the instance from the per-request Context object provided by LoopBack’s REST layer.

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

We are discussing how to make this use case easier to implement in GitHub pull request loopback-next#6793, feel free to join the discussion there.


Instead of writing an Express route for your rendered pages, I recommend you to write a LoopBack 4 Controller instead; and inject Express Response object to allow you to render the HTML view, as explained in

import {Response, RestBindings, oas} from '@loopback/rest';
import {inject} from '@loopback/core';
import {UserRepository} from '../repositories';

export class PingController {
    private response: Response

    public userRepository: UserRepository,
  ) {}

  // Hide this endpoint from OpenAPI spec generated for the app
  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;

Having said that, if you already know how to access DataSource instances from your LB4 app in your Express routes, then you can instantiate Repository classes manually from your routes too:

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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top