How create repository?

Hello,

I want create App\Repositories\UserRepository.js for example…

I Want create a common function for use in any Controllers.

I made this:

UserRepository.js:

'use strict'

const Project = use('App/Models/Project')

const Redis = use('Redis')

class ProjectRepository {

  /**
   * @param {String} app_id
   */
  async getByAppId(app_id) {

    return 'simple string'
  }
}

module.exports = ProjectRepository

Controller:

'use strict'

/** @typedef {import('@adonisjs/framework/src/Request')} Request */
/** @typedef {import('@adonisjs/framework/src/Response')} Response */
/** @typedef {import('@adonisjs/framework/src/View')} View */

const ProjectRepository = use('App/Repositories/ProjectRepository')

/**
 * Resourceful controller for interacting with projects
 */
class ProjectsController {

  /**
   * Display a single project.
   * GET /projects/:appId
   *
   * @param {object} ctx
   * @param {Request} ctx.request
   * @param {Response} ctx.response
   * @param {View} ctx.view
   */
  async show ({ params, request, response, view }) {

    let project = await ProjectRepository.getByAppId(params.app_id)

    if(project) {
      return response.json(project)
    }
    else {
      return response.json('Project not found')
    }
  }
}

module.exports = ProjectsController

But i got this error:

ProjectRepository.getByAppId is not a function
2 Likes

Hey @paulocastellano! :wave:

The method use() will not instantiate the class for you.

You have multiple possibilities here:

  1. Use make() instead, it’s the use() equivalent but it will instantiate the class.
  2. Use dependency injection via the inject() property of your controller. (example of this here: https://github.com/Lausanne-Esports/api.els.team/blob/develop/app/Controllers/Http/ArticleController.js#L21)

I was looking to the docs and inject() is from 3.2 and is not in the controllers docs in the 4.1 maybe is there another new way to do dependency injection ? just wondering.
Thanks

Or declare the functions as static if you don’t want to initiate the repository class.