diff --git a/express/server.ts b/express/server.ts index e4cf152..0160e17 100644 --- a/express/server.ts +++ b/express/server.ts @@ -1,12 +1,46 @@ import express from 'express' +import { nanoid } from 'nanoid' +import { createLinkSchema } from './src/zodSchema' +import { db } from './src/database' const app = express() const port = 1234 +app.use(express.json()) + app.get('/', (req, res) => { res.json({ message: 'Hello', data: 'World' }) }) +app.get('/link', async (req, res) => { + const shorteners = await db.selectFrom('shortener').selectAll().execute() + + res.json({ shorteners }) +}) + +app.post('/link', async (req, res) => { + const body = req.body + + const createLink = createLinkSchema.safeParse(body) + + if (!createLink.success) { + res.json({ message: 'Invalid Link', body }) + return + } + + const uuid = nanoid(10) + + await db + .insertInto('shortener') + .values({ + link: createLink.data.link, + code: uuid, + }) + .execute() + + res.json({ ...createLink.data, uuid }) +}) + app.listen(port, () => { console.log(`Listening on port ${port}...`) }) diff --git a/express/src/zodSchema.ts b/express/src/zodSchema.ts new file mode 100644 index 0000000..7efbc0c --- /dev/null +++ b/express/src/zodSchema.ts @@ -0,0 +1,5 @@ +import { z } from 'zod' + +export const createLinkSchema = z.object({ + link: z.string().url(), +})