makeomatic / restify-formatter-jsonapi

jsonapi compilant restify formatter
MIT License
2 stars 1 forks source link

how to use? #2

Open nateq314 opened 7 years ago

nateq314 commented 7 years ago

Hi, Can you please clarify what "Make sure to add this into accepts middleware" means exactly? I import it as:

jsonapi_formatter = require('restify-formatter-jsonapi');

So do you mean to do this?

server.use(restify.acceptParser(jsonapi_formatter));

Currently I'm trying:

const server = restify.createServer({
  formatters: jsonapi_formatter
}

but that doesn't seem to be working, or at least if it is I can't find the formatted JSON in the request object anywhere. Can you please clarify how this is supposed to be used exactly? Would be super grateful.

TuckerCowie commented 7 years ago

@nateq314, I've recently started using this module myelf and have figured out that restify will only invoke the custom formatter if manually set the content-type to application/vnd.api+json using the lowercase header name; Content-Type did not work for me (notice the capitalized letters). Here's an example:

// Notice I use `server.pre` instead of `server.use` so that route handlers
// have a default content-type though they can still override if needed
server.pre((req, res, next) => {
  res.header('content-type', 'application/vnd.api+json');
  res.charSet('utf-8');
  next();
};

Also, since you're passing the formatter in on creation, restify should automatically register that as an accepted type as long as you pass in the default server.acceptable value.

const server = restify.createServer({
  formatters: jsonapi_formatter
};

// This will detect the registered formatter and add it to the acceptable types
server.use(restify.acceptParser(server.acceptable));