spirit-js / spirit

Modern modular library for building web applications
http://spirit.function.run
ISC License
244 stars 18 forks source link

Return JSON response with custom status code #10

Closed ranyefet closed 7 years ago

ranyefet commented 7 years ago

Hello,

I'm building a JSON api using spirit. I've started by adding catch-all route to return 404 response.

route.get("*", {
  status: 404,
  headers: {
    'Content-Type': 'application/json'
  }
    body: JSON.stringify({
    message: 'Not Found',
  })
})

While it works, it's a little bit verbose.

Is there a shorter way to do that, maybe something like:

route.get("*", response.json(404, { message: "Not Found" }))

Thanks, Ran.

FlorianWendelborn commented 7 years ago

Why don't you implement response.json like this?

const response = {
    json: (status = 500, data) => {
        return {
            body: JSON.stringify(data),
            headers: {
                'Content-Type': 'application/json'
            },
            status
        };
    }
};
hnry commented 7 years ago

Hey @ranyefet ,

You can do route.get("*", ...) to catch GET only, or there is also route.not_found(...) which will 404 on every request regardless of method. (Ex: route.not_found("Page is not found") or notFound is camelCase alias to it.

You mentioned the explicit way, there's also @dodekeract suggestion.

You also mentioned "response.json", there is a helper function similar to that:

const {response} = require("spirit").node
const route = require("spirit-router")

const app = route.define([
  route.not_found(response(JSON.stringify({ message: "Not found" })).type("json")),
  // or
  route.get("*", response(JSON.stringify({ message: "Not found" })).type("json").status_(404))
])

Also this should work (but it doesn't, so will need to fix):

route.not_found({ message: "Not found" }) 

Which would do what you want. Will upload fix by tonight (spirit-router@0.4.0).

ranyefet commented 7 years ago

@dodekeract I know i can implement it by myself, but think it should be part of spirit it's really basic and a lot of users can benefit from helper like that.

@hnry Thanks for the suggestion but I prefer to not use JSON.stringify all over my code. Looking forward for the fix 👍

FlorianWendelborn commented 7 years ago

@ranyefet I think it should be a separate module. No need to pollute the core module with helper functions.

hnry commented 7 years ago
route.not_found({ message: "Not found" }) 
// or for GET only requests
route.not_found("get", { message: "Not found" })

will produce a response with status code 404, and json content type header set, and a json body.

Also as per your suggestion @ranyefet I updated the response helper function to be:

route.not_found(response({ message: "Not found" }).type("json"))
// or 
route.get("*", response({ message: "Not found" }).type("json").status_(404))

spirit v0.4.0 & spirit-router v0.4.0

Closing, if there's an issue or another suggestion feel free to let me know ✌️