6.031TS
6.031TS — Software Construction
TypeScript Pilot — Spring 2021

Code Examples for Reading 24

Download

You can also download a ZIP file containing this code.

Seems to be necessary to have a triple-backtick block at the start of this page,
otherwise all the pre/code tags below aren't syntax highlighted.
So create a hidden one.

server.ts

import express from 'express';
import { timeout } from './timeout';
import asyncHandler from 'express-async-handler';

const app = express();

const PORT = 8000;
app.listen(PORT);
console.log('now listening at http://localhost:' + PORT);

// GET /echo?greeting=<string>
//
// response is a greeting including <string>
app.get('/echo', function(request, response) {
    const greeting = request.query.greeting;
    response
        .status(200)
        .type('text')
        .send(greeting + ' to you too!');
});

// GET /wait
//
// waits for 5 seconds before finishing response
app.get('/wait', async function(request, response) {
    await timeout(5000);
    response
        .status(200)
        .type('text')
        .send('done');
});

// GET /bad
//
// always produces an error output
app.get('/bad', function(request, response) {
    throw new Error('oof');
});

// GET /wait-bad
//
// waits 1 second, then produces an error output
app.get('/wait-bad', asyncHandler(async function(request, response) {
    await timeout(1000);
    throw new Error('oof');
}));