Express - requireAll collection custom filter

Hello,

I’m trying to create new file organisation for my project. I need to add a custom filter for collection loading.

The loading is perform here : forest-express/index.js at 0d9c4f44ffd7bfb8291a0ceb37d31a63885a8e70 · ForestAdmin/forest-express · GitHub

function loadCollections(collectionsDir) {
  const isJavascriptOrTypescriptFileName = (fileName) =>
    fileName.endsWith('.js') || (fileName.endsWith('.ts') && !fileName.endsWith('.d.ts'));

  // NOTICE: Ends with `.spec.js`, `.spec.ts`, `.test.js` or `.test.ts`.
  const isTestFileName = (fileName) => fileName.match(/(?:\.test|\.spec)\.(?:js||ts)$/g);

  requireAll({
    dirname: collectionsDir,
    excludeDirs: /^__tests__$/,
    filter: (fileName) =>
      isJavascriptOrTypescriptFileName(fileName) && !isTestFileName(fileName),
    recursive: true,
  });
}

With the actual version we have the config collectionsDir, and i would like to have an other option collectionsFilter which is a function (fileName: string) => boolean.

With this config we could initialize Liana like this :

await Liana.init({
  configDir: path.join(__dirname, '../forest'),
  collectionFilter:  (fileName) => fileName.include('.collection.'), //match post.collection.js
  envSecret: process.env.FOREST_ENV_SECRET,
  authSecret: process.env.FOREST_AUTH_SECRET,
  objectMapping,
  connections,
})

Proposal change on forest-express
src/services/config-store.js

get collectionsFilter() {
    if (!this.lianaOptions) return null;

    const { collectionsFilter } = this.lianaOptions;
    if (collectionsFilter) {
      return collectionsFilter;
    }

    return (fileName) => true;
  }

src/index.js

function loadCollections(collectionsDir, collectionsFilter) {
  const isJavascriptOrTypescriptFileName = (fileName) =>
    fileName.endsWith('.js') || (fileName.endsWith('.ts') && !fileName.endsWith('.d.ts'));

  // NOTICE: Ends with `.spec.js`, `.spec.ts`, `.test.js` or `.test.ts`.
  const isTestFileName = (fileName) => fileName.match(/(?:\.test|\.spec)\.(?:js||ts)$/g);

  requireAll({
    dirname: collectionsDir,
    excludeDirs: /^__tests__$/,
    filter: (fileName) =>
      isJavascriptOrTypescriptFileName(fileName) && !isTestFileName(fileName) && collectionsFilter(fileName),
    recursive: true,
  });
}
  if (configStore.doesConfigDirExist()) {
    loadCollections(configStore.configDir, configStore.collectionsFilter)
  }

(you should rename configDir to collectionDir to be more logical :wink:)

Hi @Justin_Martin

I added a ticket for the feature request, but can’t commit on a deadline, as those need to be validated higher-up.

In the meantime, so that you are not stuck on your refactoring, I generated a patch file with your changes that you should be able to use in your project with https://www.npmjs.com/package/patch-package

1 Like