Skip to content

Commit

Permalink
feat(backend): add server.ts and handle process signals correctly (#11)
Browse files Browse the repository at this point in the history
Signed-off-by: Dirk de Visser <[email protected]>
  • Loading branch information
dirkdev98 authored Feb 15, 2024
1 parent 09fce8d commit 83b369b
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 1 deletion.
9 changes: 9 additions & 0 deletions apps/backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,12 @@ npm run build
npm run lint
npm run test
```

## Features

- ESLint, Typescript and test setup, see the [./package.json](./package.json) scripts.
- Graceful shutdown on exit signals via
[close-with-grace](https://npm.im/close-with-grace) in [./server.ts](./server.ts).
- Basic multipart form handling via
[@fastify/multipart](https://npm.im/@fastify/multipart) in
[./plugins/base.ts](./plugins/base.ts).
4 changes: 3 additions & 1 deletion apps/backend/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import fastify, { FastifyRequest } from "fastify";
import { basePlugin } from "./plugins/base.js";

export async function buildApp() {
const app = fastify();
const app = fastify({
logger: true,
});

app.register(basePlugin);

Expand Down
1 change: 1 addition & 0 deletions apps/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"test": "node --test"
},
"dependencies": {
"close-with-grace": "^1.2.0",
"fastify": "^4.26.0",
"fastify-plugin": "^4.5.1",
"@fastify/multipart": "^8.1.0"
Expand Down
32 changes: 32 additions & 0 deletions apps/backend/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import closeWithGrace from "close-with-grace";
import { buildApp } from "./app.js";

const app = await buildApp();

const closeGracefully = closeWithGrace({ delay: 500 }, async (options) => {
if (options.err) {
app.log.error(options.err);
}

await app.close();
});

app.addHook("onClose", (instance, done) => {
closeGracefully.uninstall();
return done();
});

const port = process.env.PORT ? Number(process.env.PORT) : 3001;

app.listen(
{
// TODO: we probly need to configure host as well for production.
port,
},
(err) => {
if (err) {
app.log.error(err);
process.exit(1);
}
},
);

0 comments on commit 83b369b

Please sign in to comment.