I’ve received an Node.js api documented with swagger for debbuging. I also have to make some features in it, but I’m having some trouble when calling, in the code, the functions executed when you hit an specific endpoint. To make my self clear:
var getCauById = async function (request, callback) { await CauModel.findById(request, function (err, result) { if (err) { callback(err); } else { callback(result); } }); }
Works fine from Swagger UI when I only give it the argument of the ID required in the request
param. Request URL example: http://localhost:8000/api/cau/{id}
works fine either.
But when I try to call it from another part of the code like this:
const caus = require("../cau") caus.getCauById("608ff7531ee4d422a201ff5a")
then I get `TypeError: callback is not a function. So what’s the callback swagger (or the endpoint execution) is providing and I’m missing. I know this is a pretty basic misunderstanding on how APIs and callbacks work, so an explanation would be really appreciated.
Thank you all!
Advertisement
Answer
You have defined getCauById as a function that takes two parameters, request and callback. But you don’t provide “callback” when you call the function. Callback needs to be a function that does something with err or result.
For example:
const caus = require("../cau") const myCallback = (resultOrError) => console.log(resultOrError); caus.getCauById("608ff7531ee4d422a201ff5a", myCallback);