If you've ever used TypeORM before, you probably know that it has a wonderful sync feature which has a look at your entity files and updates your database schema accordingly.
This is very convenient as it eliminates the dull work of creating & updating table migrations.
Typically all you'd need to do is set TypeORM settings synchronization: true
and pass an entities
property with a path to your entity definition directory.
Not Next.js friendly
This does not work nicely with Next.js for 3 reasons:
- If you pass it a path to the directory with the non-transpiled files, node simply won't be able to execute them.
- Due to how Next.js compiles server-side code, your entities will end up under the actual api route file, not in their own separate files.
- Even if you placed each entity under the
pages/api
directory (bad idea btw), in development mode they won't be compiled until requested through http.
Solution
Since we don't want to import and pass each entity file to TypeORM manually, we can go to our good friend Webpack for help.
First thing we have to do is tell Webpack to automatically include each of our entity files.
/*
* Our entity files end with '.entity.ts' and live under the
* 'api/database/entities` directory.
*/
const context = require.context('api/database/entities', true, /\.entity\.ts$/);
Now, context has the keys
method we can use to get the array of files it found under the entities directory.
/*
* e.g ['./user.entity.ts', './profile.entity.ts', ...]
*/
const entityFileNames = context.keys();
Finally, we can import these files by calling context
method itself.
/*
* We're calling `.default` to get the default export.
*/
const entities = entityFileNames.map(file => context(file).default);
Now all is left to do is to pass them to createConnection
createConnection({
...
synchronization: true,
entities
});
Et voilà, that's all we need to sync our entity files in Next.js with TypeORM.
Note: If you're using TypeScript, you'll need to add webpack's type definitions: yarn add -D @types/webpack-env
.
Conclusion
I hope this helped someone!
If you have any questions, feel free to ask.
Happy syncing ❤️
Discussion (0)