Skip to content

Instantly share code, notes, and snippets.

@carlosvega20
Created September 27, 2023 13:52
Show Gist options
  • Save carlosvega20/b6abd7b6370984e1eb4e5b3a357d4978 to your computer and use it in GitHub Desktop.
Save carlosvega20/b6abd7b6370984e1eb4e5b3a357d4978 to your computer and use it in GitHub Desktop.
const fastify = require('fastify')({ logger: true });
const mysql = require('fastify-mysql');
const Joi = require('joi'); // For request validation
// Register the fastify-mysql plugin and set up the database connection with a connection pool
fastify.register(mysql, {
connectionString: 'mysql://your_username:your_password@your_database_url/your_database_name',
pool: {
min: 0,
max: 10,
},
});
// Request validation schema using Joi
const itemSchema = Joi.object({
name: Joi.string().required(),
description: Joi.string().required(),
});
fastify.get('/api/items', async (request, reply) => {
const client = await fastify.mysql.getConnection();
try {
const [rows] = await client.query('SELECT * FROM items');
return { items: rows };
} finally {
client.release();
}
});
fastify.post('/api/items', { schema: { body: itemSchema } }, async (request, reply) => {
const { name, description } = request.body;
const client = await fastify.mysql.getConnection();
try {
await client.query('INSERT INTO items (name, description) VALUES (?, ?)', [name, description]);
return { message: 'Item created successfully' };
} finally {
client.release();
}
});
fastify.put('/api/items/:id', { schema: { params: { id: Joi.number().required() }, body: itemSchema } }, async (request, reply) => {
const { id } = request.params;
const { name, description } = request.body;
const client = await fastify.mysql.getConnection();
try {
await client.query('UPDATE items SET name = ?, description = ? WHERE id = ?', [name, description, id]);
return { message: `Item with ID ${id} updated successfully` };
} finally {
client.release();
}
});
fastify.delete('/api/items/:id', { schema: { params: { id: Joi.number().required() } } }, async (request, reply) => {
const { id } = request.params;
const client = await fastify.mysql.getConnection();
try {
await client.query('DELETE FROM items WHERE id = ?', [id]);
return { message: `Item with ID ${id} deleted successfully` };
} finally {
client.release();
}
});
fastify.listen(3000, (err) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
console.log('Server is running on port 3000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment