Closed ranyefet closed 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
};
}
};
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).
@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 👍
@ranyefet I think it should be a separate module. No need to pollute the core module with helper functions.
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 ✌️
Hello,
I'm building a JSON api using spirit. I've started by adding catch-all route to return 404 response.
While it works, it's a little bit verbose.
Is there a shorter way to do that, maybe something like:
Thanks, Ran.