Skip to content

Instantly share code, notes, and snippets.

@RichardBray
Created February 7, 2024 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RichardBray/d4aa9f94f892a2527cab4d637a48153a to your computer and use it in GitHub Desktop.
Save RichardBray/d4aa9f94f892a2527cab4d637a48153a to your computer and use it in GitHub Desktop.
Simple Hono Api
import { Hono } from 'hono';
import logger from './utils/logger';
const app = new Hono();
const fakeDB: Array<{ text: string; id: number }> = [];
app.get('/', (c) => c.text('Simple Wishlist API'));
app.get('/wishlist', (c) => {
return c.json([...fakeDB], 200);
});
app.post('/wishlist', async (c) => {
const { text } = await c.req.json<{ text: string }>();
const id = fakeDB.length + 1;
fakeDB.push({ text, id });
logger.info(`Item with id ${id} added`);
return c.json({ text, id }, 201);
});
app.delete('/wishlist/:id', (c) => {
const id = Number(c.req.param('id'));
const index = fakeDB.findIndex((item) => item.id === id);
if (index === -1) {
logger.error(`Item with id ${id} not found`);
return c.json({ message: 'Not found' }, 404);
}
fakeDB.splice(index, 1);
logger.info(`Item with id ${id} deleted`);
return c.json({ message: 'Deleted' }, 200);
});
app.put('/wishlist/:id', async (c) => {
const id = Number(c.req.param('id'));
const { text } = await c.req.json<{ text: string }>();
const index = fakeDB.findIndex((item) => item.id === id);
if (index === -1) {
logger.error(`Item with id ${id} not found`);
return c.json({ message: 'Not found' }, 404);
}
fakeDB[index].text = text;
logger.info(`Item with id ${id} updated`);
return c.json({ text, id }, 200);
});
export default app;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment