nnfans
nnfans

Reputation: 193

Fastify plugin fastify-autoload error plugin must be a function

I have setup the fastify framework with fastify-cli library with command fastify-cli generate. It has fastify-autoload plugin used out of the box.

But, it will throw an error when I add my own service with exception for model.js and schema.js files.

...
fastify.register(AutoLoad, {
    dir: path.join(__dirname, 'services'),
    options: Object.assign({}, opts),
    ignorePattern: /.*(model|schema)\.js/
})
...

Error message:

assert.js:788
    throw newErr;
    ^

AssertionError [ERR_ASSERTION]: ifError got unwanted exception: plugin must be a function
    at wrap (D:\project\kuisioner\backend\node_modules\fastify-cli\start.js:124:5)
    ...
      actual: Error: plugin must be a function
    ...
    error Command failed with exit code 1.
    ...

But it will run smoothly when I register it manually

...
fastify.register(require('./services/quiz/get'))
fastify.register(require('./services/quiz/post'))
...

My file structure:

- src
  - plugins
    - db.js
  - services
  | - quiz
  |   - get.js
  |   - model.js
  |   - post.js
  |   - schema.js
  - app.js

I use fastify-cli fastify start -l info src/app.js to run my code

Here's my repo https://github.com/nnfans/kuisionerid_backend

Upvotes: 4

Views: 9695

Answers (4)

Alessander Franca
Alessander Franca

Reputation: 2763

according to docs, if you are using node with tsx you should change your command:

node --import=tsx server.ts

for

tsx server.ts

Upvotes: 0

Milan Karunarathne
Milan Karunarathne

Reputation: 100

May be If you have accidentally create a empty route file this issue will happens and it persist on the dist ( Mostly you are using TypeScript ) This empty route file not returning functional output. As yonadav bar ilan said you have to delete dist and try to re-run it.

Upvotes: 1

yonadav bar ilan
yonadav bar ilan

Reputation: 629

if you got here and you use typescript, maybe try to delete the dist dir and re-run tsc, you might have had a bad route that persisted there

Upvotes: 5

Manuel Spigolon
Manuel Spigolon

Reputation: 12900

Checking your repo the error is the dir value. You must point to the dir with the files, it is not supported the recursive loading yet

  fastify.register(AutoLoad, {
    dir: path.join(__dirname, 'services/quiz'), 
    options: Object.assign({}, opts),
    ignorePattern: /.*(model|schema)\.js/
  })

With this change, the npm start will work.

Another option is to use module.exports.autoload = false in the files that need to be skipped, but your regex is ok.

Upvotes: 7

Related Questions