Responses
Build responses with the spongRes helpers, or return a standard Response.
A handler must return a Response. The spongRes helper builds one for you, and you can always return a standard Response instead.
TypeScript
bob.spongGet('/ok', async (spongReq, spongRes) => spongRes.json({ ok: true }))bob.spongGet('/raw', async () => new Response('plain text'))The basics
| Helper | Description |
|---|---|
send(body) | Sends a text body with the current status. The content type is text/plain; charset=utf-8 unless you set one. |
json(data, status?) | Sends JSON. The status defaults to the one set with status(). |
status(code) | Sets the status and returns spongRes, so it can be chained. |
header(name, value) | Sets a header and returns spongRes, so it can be chained. |
TypeScript
return spongRes .status(201) .header('X-Request-Source', 'docs') .json({ created: true })Status helpers
Every common status has a named helper that returns a ready Response. Success and error helpers take optional data and fall back to a sensible default body.
| Family | Examples | Default body |
|---|---|---|
| 2xx success | SpongOK(data?), SpongCreated(data?), SpongAccepted(data?), SpongPartialContent(data?), SpongNoContent() | { message: 'OK' }, { message: 'Created' }, { message: 'Accepted' }, {} for the rest |
| 3xx redirects | SpongMovedPermanently(url?), SpongFound(url?), SpongSeeOther(url?), SpongTemporaryRedirect(url?), SpongPermanentRedirect(url?) | A Location header, / by default |
| 4xx client errors | SpongBadRequest(data?), SpongUnauthorized(data?), SpongForbidden(data?), SpongNotFound(data?), SpongConflict(data?), SpongUnprocessableContent(data?), SpongTooManyRequests(data?) | { error: 'Bad Request' }, { error: 'Unauthorized' }, { error: 'Forbidden' }, { error: 'Not Found' }, {} for the rest |
| 5xx server errors | SpongInternalServerError(data?), SpongBadGateway(data?), SpongServiceUnavailable(data?) | { error: 'Internal Server Error' } |
TypeScript
bob.spongGet('/users/:id', async (spongReq, spongRes) => { const user = await findUser(spongReq.params.id) if (!user) return spongRes.SpongNotFound({ error: 'User not found' }) return spongRes.SpongOK(user)})Use SpongUnprocessableContent (422) to answer a failed validation, and SpongCreated (201) after creating something. Every name follows the standard status text with a Spong prefix.
Pick one response shape
The helpers accept any data, so the shape of your JSON is yours to choose. Choose one and keep it everywhere. The example apps in these docs use this shape:
Output
// success{ "success": true, "data": { ... } } // failure{ "success": false, "message": "Task not found" } // validation failure{ "success": false, "message": "Validation failed", "errors": { "title": ["title is required"] } }