Registering models
- Cases where you should add a models registry
- Adding a registry to your action factory
- Registering models
When should you use a registry?
A Registry is a simple object which will store your models classes and let
Foscia resolves models from their type string.
As stated in the models guide, you may need this object when your models contains circular references, because you won't be able to import models when strictly following some code style (e.g. ESLint AirBnB disallow dependency cycle).
Adding registry
Defining models list
First, you will need to define a models list which default export an array of all your available models.
Using CLI (recommended)
- NPM
- YARN
- PNPM
- Bun
npx foscia make models
yarn foscia make models
pnpm foscia make models
bun foscia make models
If you choose the "Manually" option, you can rerun this command to update your models list file.
You can also pass the --models option when calling
foscia make model <name> to
automatically update the file after creating the model file.
Manually
import Post from './post';
import User from './user';
export default [
Post,
User,
];
Adding registry to action factory
Foscia provides a simple implementation for the registry through
makeRegistry
(providing using makeRegistry factory function).
import { makeActionFactory, makeRegistry } from '@foscia/core';
import models from './models';
export default makeActionFactory({
// Add the registry to your action factory.
...makeRegistry(models),
// ...
});
When adding the registry, you can also provide a type normalization function to normalize local/data source models' types.
makeRegistry(models, {
normalizeType: (type: string) => pluralize(toCamelCase(type)),
});
Listing models
Here are some suggestion on how you can list your models classes easily without generating a file using the CLI.
Using an array
This is the most simple and common way of listing the models classes.
import Post from './post';
import User from './user';
export default [Post, User];
Using import.meta.global
This method can be used with some bundlers, such as ViteJS, and will provide you an automatic registration if your models are in the same directory.
For this, we will assume all models classes are located in a models directory.
import { Model } from '@foscia/core';
export default Object.values(import.meta.glob('./models/*.ts', {
import: 'default,
eager: true,
}) as { [k: string]: Model });
Using require.context
This method can be used with some bundlers, such as Webpack, and will provide you an automatic registration if your models are in the same directory.
For this, we will assume all models classes are located in a models directory.
import { Model } from '@foscia/core';
export default ((context: any) => context.keys().map(
(key: any) => context(key).default as Model,
))(require.context('./models', true, /\.ts/));