0

I'm trying fastify with fastify-bookshelfjs.

contact (model)

module.exports = async function (fastify) {
  console.log("4")
  fastify.bookshelf.Model.extend({
    tableName: 'contacts',
  })
}

contact (controller)

console.log("3")
const Contact = require('../models/contact')()

// Get all contact
async function getContact(req, reply) {
        const contacts = Contact.fetchAll()
        reply.code(200).send(contacts)
}
module.exports = getContact

contact (routes)

module.exports = async function (fastify) {
  console.log("2")
  const contact = require('../controller/contact')

  fastify.get('/', contact.getContact)
}

When the server start I get this output

2
3
4
(node:10939) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'bookshelf' of undefined
1
server listening on 3000

Why fastify in contact(model) is undefined and how can fix ?

Phan
  • 115
  • 1
  • 7

1 Answers1

0

In your controller, when you import the model, you need to put fastify as argument.

Also, you have to import the fastify module.

Your contact (controller) should be

const fastify = require('fastify') // import the fastify module here
console.log("3")
const Contact = require('../models/contact')(fastify)

// Get all contact
async function getContact(req, reply) {
        const contacts = Contact.fetchAll()
        reply.code(200).send(contacts)
}
module.exports = getContact
Shams Nahid
  • 6,239
  • 8
  • 28
  • 39