Skip to content

Commit

Permalink
Merge pull request #116 from eik-lib/custom-404
Browse files Browse the repository at this point in the history
feat: Set custom 404 handler
  • Loading branch information
trygve-lie authored Oct 27, 2020
2 parents 4f97330 + b57c9f8 commit 22e6eff
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,11 +164,19 @@ const EikService = class EikService {
global: config.get('compression.global'),
});

// 404 handling
app.setNotFoundHandler((request, reply) => {
reply.header('cache-control', 'no-store');
reply.type('text/plain');
reply.code(404);
reply.send('Not found');
});

// Error handling
app.setErrorHandler((error, request, reply) => {
this.logger.debug('Error occured during request. Error is available on trace log level.');
this.logger.trace(error);

reply.header('cache-control', 'no-store');
if (error.statusCode) {
reply.send(error);
return;
Expand Down
54 changes: 54 additions & 0 deletions test/404.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
'use strict';

const FormData = require('form-data');
const fastify = require('fastify');
const fetch = require('node-fetch');
const tap = require('tap');

const Server = require("..");
const Sink = require('../node_modules/@eik/core/lib/sinks/test');

tap.test('404 - POST request to non existing pathname', async (t) => {
const sink = new Sink();
const service = new Server({ customSink: sink });

const app = fastify({
ignoreTrailingSlash: true,
});
app.register(service.api());

const address = await app.listen(0, 'localhost');

const formData = new FormData();
formData.append('key', 'change_me');

const response = await fetch(`${address}/non/existent`, {
method: 'POST',
body: formData,
headers: formData.getHeaders(),
});

t.equals(response.status, 404, 'server should respond with a 404 Not found');
t.equals(response.headers.get('cache-control'), 'no-store', 'should contain "cache-control" set to "no-store"');

await app.close();
});

tap.test('404 - GET request to non existing pathname', async (t) => {
const sink = new Sink();
const service = new Server({ customSink: sink });

const app = fastify({
ignoreTrailingSlash: true,
});
app.register(service.api());

const address = await app.listen(0, 'localhost');

const response = await fetch(`${address}/non/existent`);

t.equals(response.status, 404, 'server should respond with a 404 Not found');
t.equals(response.headers.get('cache-control'), 'no-store', 'should contain "cache-control" set to "no-store"');

await app.close();
});

0 comments on commit 22e6eff

Please sign in to comment.