Skip to content

Commit

Permalink
✨ Added templating system
Browse files Browse the repository at this point in the history
  • Loading branch information
lukecarr committed Nov 17, 2021
1 parent 93ada21 commit a2a7af4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,22 @@ const { withError } = require("@moducate/houston");
const app = require("express")();

app.get("/not-found", (_, res) => {
return withError(res, { type: "https://example.com/not-found", status: 404 })
return withError(res, { type: "https://example.com/not-found", status: 404 });
});
```

## 📄 Templates

You can create error templates using the exported `withTemplate` function:

```js
const { withTemplate } = require("@moducate/houston");
const app = require("express")();

const withNotFound = withTemplate({ type: "https://example.com/not-found", status: 404 });

app.get("/not-found", (_, res) => {
return withNotFound(res); // The second parameter is optional when using templates
});
```

Expand Down
12 changes: 12 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,15 @@ export function withError (res: ServerResponse, err: Partial<Error>): void {
}
return res.setHeader('Content-Type', mime).end(JSON.stringify(err))
}

/**
* Generates an RFC 7807 compliant error template which can be invoked to
* make errors with common values.
*
* @param template The template's values.
* @returns A `withError` function which can be invoked to apply the error
* template to a `http.ServerResponse` object.
*/
export function withTemplate (template: Partial<Error>): (res: ServerResponse, err?: Partial<Error>) => void {
return (res, err) => withError(res, { ...template, ...err })
}

0 comments on commit a2a7af4

Please sign in to comment.