2

I'm parsing all the modules in a directory, initialise them, and finally export them. The modules in question are knex models like this one:

// schema/users.js

import createModel from './common'

const name = 'User'
const tableName = 'users'

const selectableProps = ['userId', 'name', 'email', 'updated_at', 'created_at']

export default knex => {
  const model = createModel({
    knex,
    name,
    tableName,
    selectableProps,
  })

  return { ...model }
}

Each of the model definitions is extended with common parts:

// schema/common.js
export default ({
  knex = {},
  name = 'name',
  tableName = 'tablename',
  selectableProps = [],
  timeout = 1000,
}) => {
  const findAll = () =>
    knex
      .select(selectableProps)
      .from(tableName)
      .timeout(timeout)

  return {
    name,
    tableName,
    selectableProps,
    timeout,
    findAll,
  }
}

Finally, all models are initialised and exported:

// schema/index.js
import { readdir } from 'fs'
import { promisify } from 'util'
import { default as knex } from '../db'

let modules = {}

export default new Promise(async $export => {
  const readFileAsync = promisify(readdir)

  const getModels = async dir => await readFileAsync(dir)

  const files = await getModels(__dirname)

  for await (const file of files) {
    if (file !== 'common.js' && file !== 'index.js') {
      let mod = await import(__dirname + '/' + file).then(m => m.default(knex))
      modules[mod.name] = mod
    }
  }

  await $export(modules)
  console.log(modules)
})

The above seem to be working but I'm not able to figure out how to import one of these modules from another file. I'm trying to do something along the lines of:

const User = async () => await import('../schema') // not working

or

const User = (async () => await import('../schema'))() // not working

Any help with this will be appreciated!

boojum
  • 669
  • 2
  • 9
  • 31

0 Answers0