lucid icon indicating copy to clipboard operation
lucid copied to clipboard

Dynamic import of Models

Open venki0004 opened this issue 5 years ago • 4 comments

Package version

V5

Node.js and npm version

Nodejs :14.15, npm : 6.14.8

Sample Code (to reproduce the issue)

I want to create FindById middleware to get record

Route.get('/:id', 'TemplateController.show').middleware('findById:Template')


import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

export default class FindById {
  public async handle(
    { request, response }: HttpContextContract,
    next: () => Promise<void>,
    model: string
  ) {
    // code for middleware goes here. ABOVE THE NEXT CALL
    const id = request.param('id')
    const Instance = await import(`App/Models/${model}`)
    const record = await Instance.query().where('id', id).first()

    if (!record) {
      return response.notFound({ message: `${model} not found.` })
    }
    request[model.toLowerCase()] = record
    await next()
  }
}


BONUS (a sample repo to reproduce the issue)

its throwing following error image

my codebase Model: image

venki0004 avatar Jun 20 '21 07:06 venki0004

Cannot reproduce. Please provide a sample project repo to help reproduce the issue

thetutlage avatar Jun 30 '21 14:06 thetutlage

Closing since no response from the issue reporter and not actionable as well

thetutlage avatar Jul 04 '21 05:07 thetutlage

Hi. Although it already closed, with relative path works for me:

const instance = await import(`../../Models/${model}`).then((m) => m.default)
const record = await instance.query().where('id', id).first()

pierresilva avatar Aug 06 '22 02:08 pierresilva

Sure! Here's your GitHub issue answer rewritten in clear, professional English, suitable for submitting as a helpful comment or solution:


✅ Dynamic Model Import in AdonisJS Without Manual Imports

🎯 Problem

Sometimes we need to load AdonisJS models dynamically—without importing each one manually—especially when building generic services or factories.


🛠️ Solution

  1. Create a preload file using the AdonisJS CLI:

    node ace make:preload model
    

    This will create a file at:

    start/model.ts
    
  2. Edit start/model.ts with the following code:

    // start/model.ts
    declare global {
      var getModel: (name: string) => Promise<any>
    }
    
    global.getModel = async (name: string) => {
      const module = await import(`../app/Models/${name}.ts`)
      return module.default
    }
    

    📌 Note: The relative path assumes your models are located in app/Models/. Adjust as needed based on your project structure.


✅ Usage Example

You can now dynamically load and use any model like this:

const User = await getModel('User')
const users = await User.all()

This removes the need to manually import models in each file.


💡 Optional: Fallback for Production Builds

If you're running a production build (node build) and your files are compiled to .js, you can add a fallback:

global.getModel = async (name: string) => {
  try {
    const module = await import(`../app/Models/${name}.ts`)
    return module.default
  } catch {
    const module = await import(`../app/Models/${name}.js`)
    return module.default
  }
}

📦 Benefits

  • No need to import each model manually
  • Cleaner and more scalable code
  • Great for dynamic services, admin generators, or resolving models by name

nazruldev avatar Apr 04 '25 05:04 nazruldev