nodejs-warsaw-xxi/src/example1.ts

57 lines
No EOL
1.1 KiB
TypeScript

import fastify from 'fastify';
const app = fastify({ logger: true });
interface User {
id: number;
name: string;
email: string;
age: number;
}
app.post<{ Body: User; }> ('/api/users', async (request, reply) => {
const user = request.body;
const canDrink = user.age >= 21;
const greeting = `Hello ${user.name.toUpperCase()}, your email ${user.email.toLowerCase()} has been recorded`;
return { user, canDrink, greeting };
});
const start = async () => {
try {
await app.listen({ port: 3000 });
console.log('Server running at http://localhost:3000');
} catch (err) {
app.log.error(err);
process.exit(1);
}
};
start();
/*
Try making a POST request with this "deranged" JSON:
{
"id": "42",
"name": 12345,
"email": {"address": "bad@example.com"},
"age": "twenty-one"
}
What happens:
1. TypeScript is happy at compile time (we said body is User)
2. Fastify accepts this JSON as valid (no runtime validation)
3. Code fails when trying operations like toUpperCase() on a number
or comparing "twenty-one" >= 21
*/