init
This commit is contained in:
18
src/main.ts
Normal file
18
src/main.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import express, { json } from 'express';
|
||||
import { handleError } from './utils/errorHandler'
|
||||
import 'dotenv/config'
|
||||
|
||||
import { router } from './routes'
|
||||
|
||||
const app = express();
|
||||
|
||||
const port = process.env.PORT || 3000;
|
||||
|
||||
app.use(json({ limit: '100kb' }))
|
||||
|
||||
app.use(router)
|
||||
|
||||
app.use(handleError)
|
||||
app.listen(port, () => {
|
||||
console.log(`App is running on port http://localhost:${port}`);
|
||||
})
|
||||
11
src/routes/index.ts
Normal file
11
src/routes/index.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { Router } from "express";
|
||||
|
||||
import pkg from '../../package.json'
|
||||
|
||||
import { router as usersRouter } from './users'
|
||||
|
||||
export const router = Router();
|
||||
|
||||
router.get('/healthcheck', (req, res) => void res.send({ ok: true, version: pkg.version }));
|
||||
|
||||
router.use('/users', usersRouter)
|
||||
40
src/routes/users/index.ts
Normal file
40
src/routes/users/index.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { Router } from "express";
|
||||
import { Validator } from "express-json-validator-middleware";
|
||||
|
||||
export const router = Router();
|
||||
|
||||
const { validate } = new Validator({ });
|
||||
|
||||
const user = {
|
||||
type: "object",
|
||||
required: ["name"],
|
||||
properties: {
|
||||
name: {
|
||||
type: "string"
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
let users = [
|
||||
{ id: 1, name: 'John' },
|
||||
{ id: 2, name: 'Jane' },
|
||||
];
|
||||
|
||||
const addUser = (user) => new Promise<void>((res, rej) => {
|
||||
setTimeout(() => {
|
||||
// rej(new Error('user is not a spoon'));
|
||||
users.push(user);
|
||||
res();
|
||||
}, 100)
|
||||
})
|
||||
|
||||
router.get('/', (req, res) => void res.send(users));
|
||||
router.post('/', async (req, res) => {
|
||||
await addUser(req.body);
|
||||
res.send(users);
|
||||
})
|
||||
|
||||
router.delete('/:id', validate(''), (req, res, next) => {
|
||||
users = users.filter(user => user.id !== Number(req.params.id));
|
||||
res.send(users);
|
||||
})
|
||||
3
src/utils/errorHandler.ts
Normal file
3
src/utils/errorHandler.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export const handleError = (error, req, res, next) => {
|
||||
res.send({ error: error.message })
|
||||
}
|
||||
Reference in New Issue
Block a user