fastify-esm-loader
An esm-based loader for your Fastify applications.
npm i fastify-esm-loader --save
Features
- Automatically discovers route handlers from file system
- Introduces handy idioms and helpers for dependency injection
- Forces a clean, well organized style for route handler definitions
Example
npm icd example/node index.js
Usage
const fastify = fastify
You can also use injections
to make available things like db
and redis
.
Check examples/index.js
and examples/main.js
for the full boilerplate.
Assuming baseDir
is routes
, fastify-esm-loader
will recursively look for
index.js
files use them to register routes, at any depth. Take for example
project/routes/users/index.js -- here users
is a route group -- you
can have multiple route groups under baseDir
. This file must export a function
with a signature like this:
{ fastify fastify fastify}
For that to work, you'd have to have three files under routes/users
:
project/routes/users/listUser.js
project/routes/users/createUser.js
project/routes/users/createUser.js
And each of these files, export a default function that is then used as a route
handler. The loader will make them available in self
in the main route
definition function (users/index.js
), so that you can easily tweak the mapping.
The mechanics described above will work for both top-level files and subfolders.
That means the following setup work would the same:
project/routes/index.js
project/routes/topLevelMethod.js
project/routes/users/listUser.js
project/routes/users/createUser.js
project/routes/users/createUser.js
Handlers
There are two ways to define a handler:
- A function that returns the handler, useful for injections (and environment access):
{ return async { reply }}
- A direct handler export:
{ reply}
Environment shorthand
NODE_ENV
is used to populate env.$node_env
(lowercase, prefixed with $
).
This allows for checks such as this:
{ if env$staging fastify }
License
MIT