|
| 1 | +import * as express from "express" |
| 2 | +import * as bodyParser from "body-parser" |
| 3 | +import { Request, Response } from "express" |
| 4 | +import { AppDataSource } from "./data-source" |
| 5 | +import { Routes } from "./routes" |
| 6 | +import { User } from "./entity/User" |
| 7 | + |
| 8 | +AppDataSource.initialize().then(async () => { |
| 9 | + |
| 10 | + // create express app |
| 11 | + const app = express() |
| 12 | + app.use(bodyParser.json()) |
| 13 | + |
| 14 | + // register express routes from defined application routes |
| 15 | + Routes.forEach(route => { |
| 16 | + (app as any)[route.method](route.route, (req: Request, res: Response, next: Function) => { |
| 17 | + const result = (new (route.controller as any))[route.action](req, res, next) |
| 18 | + if (result instanceof Promise) { |
| 19 | + result.then(result => result !== null && result !== undefined ? res.send(result) : undefined) |
| 20 | + |
| 21 | + } else if (result !== null && result !== undefined) { |
| 22 | + res.json(result) |
| 23 | + } |
| 24 | + }) |
| 25 | + }) |
| 26 | + |
| 27 | + // setup express app here |
| 28 | + // ... |
| 29 | + |
| 30 | + // start express server |
| 31 | + app.listen(3000) |
| 32 | + |
| 33 | + // insert new users for test |
| 34 | + // await AppDataSource.manager.save( |
| 35 | + // AppDataSource.manager.create(User, { |
| 36 | + // firstName: "Timber", |
| 37 | + // lastName: "Saw", |
| 38 | + // age: 27 |
| 39 | + // }) |
| 40 | + // ) |
| 41 | + |
| 42 | + // await AppDataSource.manager.save( |
| 43 | + // AppDataSource.manager.create(User, { |
| 44 | + // firstName: "Phantom", |
| 45 | + // lastName: "Assassin", |
| 46 | + // age: 24 |
| 47 | + // }) |
| 48 | + // ) |
| 49 | + |
| 50 | + console.log("Express server has started on port 3000. Open http://localhost:3000/users to see results") |
| 51 | + |
| 52 | +}).catch(error => console.log(error)) |
0 commit comments