ForestAdmin / forest-express

🧱 Dependency of Express Lianas for Forest Admin

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to load the collections statically

ferjul17 opened this issue · comments

Expected behavior

I would like to build my forest admin project with esbuild into a single js file. That's almost working perfectly.
However, I have defined actions in some collections. I would like to import statically these collections otherwise esbuild won't bundle them.

Actual behavior

Currently, the only way to import collections is by providing a configDir in LianaOptions. This will load dynamically (through a call to requireAll()) all the files in the provided directory.

Failure Logs

N/A

Context

I'm using forest-express-sequelize@8.5.7 which requires forest-express@9.5.1.

Here is my attempt:

const lianaOptions: LianaOptions = {
  authSecret: readFromEnv('FOREST_AUTH_SECRET'),
  // configDir will load dynamically js files. It is replaced by the explicit import of ../forest
  configDir: `pathWhichMustNotExist${Math.random()}`,
  connections,
  envSecret: readFromEnv('FOREST_ENV_SECRET'),
  objectMapping,
  schemaDir: join(__dirname, '../..'),
};

require('../forest');
app.use(await init(lianaOptions));

require('../forest') imports a call to the function collection() like this:

collection('contracts', {
  actions: [
    // ...
  ],

It does not work because Schemas.schemas was not yet initialized and the collection is not loaded (see https://github.com/ForestAdmin/forest-express/blob/main/src/index.js#L402).

If I require the collection after the initialization, the schema .forestadmin-schema.json has been written and does not include the actions.

If we could have a (asynchronous) function to load the collections in addition to the configDir that would solve my problem.

Maybe something like:

if (configStore.doesConfigDirExist()) {
  loadCollections(configStore.configDir);
}

if (typeof configStore.loadCollections === 'function') {
  await configStore.loadCollections();
}

I would appreciate your help or feedbacks. If you like the idea, I can create a PR.