我试图在NodeJS api中使用服务以使我的API易于测试,但是当我注入服务(类)时,它告诉我方法getTasks()
不存在。
路线
const TodoService = require('../../services/todo');
const todo = router => {
router.get('/tasks', async (req, res, next) => {
try {
const { message, tasks, status } = await TodoService.getTasks();
return res.status(201).json({ message, tasks, status });
} catch (e) {
return next(e);
}
});
};
module.exports = todo;
服务
const TaskModel = require('../models/task');
class TodoService {
async getTasks() {
try {
const tasks = await TaskModel.find();
return {
message: 'Fetched posts successfully.',
tasks: tasks,
status: 200
};
} catch (err) {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
}
}
}
module.exports = TodoService;
我去http://localhost:3000/api/tasks
时遇到此错误:
TypeError:TodoService.getTasks不是函数
答案 0 :(得分:1)
getTasks
是在实例TodoService
上的一种方法-您尚未创建一个实例,例如new TodoService()
实例化一个实例
await new TodoService().getTasks();
或者,使getTasks static
const TaskModel = require('../models/task');
class TodoService {
static async getTasks() {
try {
const tasks = await TaskModel.find();
return {
message: 'Fetched posts successfully.',
tasks: tasks,
status: 200
};
} catch (err) {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
}
}
}
module.exports = TodoService;
或者考虑到TodoService看起来甚至不应该实例化的事实,并且这就是我要使用显示的代码来实现的方式,请将TodoService变成一个简单的对象
const TaskModel = require('../models/task');
const TodoService = {
async getTasks() {
try {
const tasks = await TaskModel.find();
return {
message: 'Fetched posts successfully.',
tasks: tasks,
status: 200
};
} catch (err) {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
}
}
}
module.exports = TodoService;