Reputation: 609
I am currently trying to add a service layer to my NodeJS project, which is a simple API I build using express and sequelize. The project has a structure of the usual model, route, and controller (MRC) form; each has its own directory. Now all I need to do is add another directory that will contain the service files. The files will contain the business logic in the form of a class that I will export and include in my controller files.
Here I will display the controller and service files:
eruptionController.js
const EruptionService = require('../services/eruptionService.js');
let Eruption = new EruptionService()
module.exports = {
getEruptions: (req, res) => {
Eruption.get().then(result => {
return res.status(200).json({
message: "Get All Eruptions",
result
})
}).catch(err => {
return res.status(200).json({
message: "internal Server Error",
error: err.message
})
})
}
};
eruptionService.js
const { eruption } = require('../models');
class EruptionService {
constructor () {
this.eruptionModel = eruption;
}
get () {
this.eruptionModel.findAll()
.then(result => result)
.catch(err => err)
}
}
module.exports = EruptionService;
As we can see here, in the service file, I imported the eruption
model from the model folder and include it in the constructor. Then I created a method named get
, which purpose to retrieve all the eruption data from the database.
After that, I imported the EruptionService
class into the controller file, initiated it as an instance, and include the class in the getEruptions
function. The function will then be used in an express route in the form of an endpoint.
The issue is that when I tried to send a request to the endpoint, I got the following error
TypeError: Cannot read property 'then' of undefined
Based on the error, it seems that the EruptionService
class was not exported properly since when I called the mothed get
it's undefined.
I've been stuck with this for a while now, and I'm not really sure what's going on. Based on this post, I seem to be exporting the class properly.
I've also tried exporting in a way like below
module.exports = {EruptionService: EruptionService}
And I've also tried importing like
const EruptionService = require('../services/eruptionService.js');
But in the end, it either results in the same error or different one kind of error. I was wondering if anybody could point out what I was missing? Thanks in advance
Upvotes: 0
Views: 1400
Reputation: 685
You should return a promise function for getting the then function inside it. There is a issue in your service it should be like the below snippet
class EruptionService {
constructor () {
this.eruptionModel = eruption;
}
get () {
return this.eruptionModel.findAll()
}
}
Upvotes: 1