|
| 1 | +import {NextFunction, Request, Response} from "express"; |
| 2 | +import {logger} from "../logger"; |
| 3 | +import {AppDataSource} from "../data-source"; |
| 4 | +import {Course} from "../models/course"; |
| 5 | + |
| 6 | +/* |
| 7 | +* |
| 8 | +* curl -X POST http://localhost:9000/api/courses -H "Content-Type:application/json" -d '{"url": "firebase-bootcamp", "title": "Firebase Bootcamp", "iconUrl": "https://angular-university.s3-us-west-1.amazonaws.com/course-images/firebase-course-1.jpg","longDescription": "Complete guided tour to the Firebase ecosystem.", "category": "BEGINNER"}' |
| 9 | +* |
| 10 | +* {"url": "firebase-bootcamp", "title": "Firebase Bootcamp", "iconUrl": "https://angular-university.s3-us-west-1.amazonaws.com/course-images/firebase-course-1.jpg","longDescription": "Complete guided tour to the Firebase ecosystem.", "category": "BEGINNER"} |
| 11 | +* |
| 12 | +* */ |
| 13 | + |
| 14 | +export async function createCourse( |
| 15 | + request: Request, response: Response, next:NextFunction) { |
| 16 | + |
| 17 | + try { |
| 18 | + |
| 19 | + logger.debug(`Called createCourse()`); |
| 20 | + |
| 21 | + const data = request.body; |
| 22 | + |
| 23 | + if (!data) { |
| 24 | + throw `No data available, cannot save course.`; |
| 25 | + } |
| 26 | + |
| 27 | + const course = await AppDataSource.manager.transaction( |
| 28 | + "REPEATABLE READ", |
| 29 | + async (transactionalEntityManager) => { |
| 30 | + |
| 31 | + const repository = transactionalEntityManager.getRepository(Course); |
| 32 | + |
| 33 | + const result = await repository |
| 34 | + .createQueryBuilder("courses") |
| 35 | + .select("MAX(courses.seqNo)", "max") |
| 36 | + .getRawOne(); |
| 37 | + |
| 38 | + const course = repository |
| 39 | + .create({ |
| 40 | + ...data, |
| 41 | + seqNo: ( result?.max ?? 0 ) + 1 |
| 42 | + }); |
| 43 | + |
| 44 | + await repository.save(course); |
| 45 | + |
| 46 | + return course; |
| 47 | + } |
| 48 | + ); |
| 49 | + |
| 50 | + response.status(200).json({course}); |
| 51 | + |
| 52 | + } |
| 53 | + catch(error) { |
| 54 | + logger.error(`Error calling createCourse()`); |
| 55 | + return next(error); |
| 56 | + } |
| 57 | + |
| 58 | +} |
0 commit comments