Patricio Vargas
Patricio Vargas

Reputation: 5522

TypeError XXX is not a function in NodeJS

I'm trying to use a service in my NodeJS api to make my API easier to test, but when I inject the service (class) it tells me the method getTasks() doesn't exist.

ROUTE

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;

SERVICE

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;

When I go to http://localhost:3000/api/tasks I get this error:

TypeError: TodoService.getTasks is not a function

Upvotes: 0

Views: 845

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

getTasks is a method on an instance of TodoService - you haven't created one, i.e. like new TodoService()

either instantiate an instance

await new TodoService().getTasks();

or, make 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;

or given the fact that TodoService doesn't look like it should even be instantiated, and this is the way I'd do it with the code you've shown, make TodoService a simple Object

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;

Upvotes: 2

Related Questions