This repository was archived by the owner on Aug 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
[WIP] Node backend for API service #157
Open
liumcse
wants to merge
4
commits into
master
Choose a base branch
from
node-backend
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,7 +5,7 @@ | |
| **/venv | ||
|
|
||
| # build | ||
| www/dist | ||
| **/dist | ||
|
|
||
| # cache | ||
| **/__pycache | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| web: node dist/api_v2/app.js |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| // import "module-alias/register"; | ||
| import * as express from "express"; | ||
| import * as cors from "cors"; | ||
| import * as routes from "./routes"; | ||
| import { logger } from "../shared/logger"; | ||
|
|
||
| const app = express(); | ||
| const port = process.env.PORT || 3000; | ||
|
|
||
| // Add middleware | ||
| app.use(cors()); | ||
| app.use(routes.courses); | ||
|
|
||
| app.listen(port, () => { | ||
| logger.info(`Server running on port ${port}`); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| import { logger } from "../../shared/logger"; | ||
| import { DB_URI } from "../../shared/config"; | ||
| import { MongoClient, Db } from "mongodb"; | ||
|
|
||
| // The singleton MongoClient object | ||
| let client: MongoClient; | ||
| // The singleton DB object | ||
| let db: Db; | ||
|
|
||
| /** Connects to database. */ | ||
| export async function connectToDb() { | ||
| try { | ||
| if (!client) { | ||
| client = new MongoClient(DB_URI, { | ||
| useNewUrlParser: true, | ||
| useUnifiedTopology: true, | ||
| }); | ||
| } | ||
| if (!client.isConnected()) { | ||
| await client.connect(); | ||
| } | ||
| } catch (e) { | ||
| logger.error("Failed to connect to database"); | ||
| logger.error(e); | ||
| } | ||
| } | ||
|
|
||
| /** Returns a database instance. */ | ||
| export async function getDbInstance() { | ||
| if (!db) { | ||
| await connectToDb(); | ||
| db = client.db("db"); | ||
| } | ||
| return db; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| import { getDbInstance } from "../libs/db"; | ||
|
|
||
| type CourseSnippet = { | ||
| course_code: string; | ||
| course_title: string; | ||
| postgrad: boolean; | ||
| }; | ||
|
|
||
| type CourseDetail = { | ||
| course_code: string; | ||
| au: number; | ||
| course_title: string; | ||
| constraint: { | ||
| prerequisite: string[]; | ||
| na_to: string[]; | ||
| na_to_all: string[]; | ||
| mutex: string; | ||
| }; | ||
| as_ue?: boolean; | ||
| as_pe?: boolean; | ||
| pass_fail: boolean; | ||
| semesters: string[]; | ||
| description: string; | ||
| last_update: Date; | ||
| postgrad: boolean; | ||
| }; | ||
|
|
||
| export async function getAllCourseSnippet(): Promise<Array<CourseSnippet>> { | ||
| // Connect to Db and get collection | ||
| const db = await getDbInstance(); | ||
| const collection = db.collection("courses"); | ||
|
|
||
| // Query database | ||
| const result: Array<CourseSnippet> = await collection | ||
| .aggregate<CourseSnippet>([ | ||
| { | ||
| $project: { | ||
| _id: 0, | ||
| course_code: 1, | ||
| course_title: 1, | ||
| postgrad: 1, | ||
| }, | ||
| }, | ||
| ]) | ||
| .toArray(); | ||
|
|
||
| // Return result | ||
| return result; | ||
| } | ||
|
|
||
| export async function getCourseDetailByCourseCode( | ||
| courseCode: string | ||
| ): Promise<CourseDetail | null> { | ||
| // Connect to Db and get collection | ||
| const db = await getDbInstance(); | ||
| const collection = db.collection("courses"); | ||
|
|
||
| // Pre-process course code | ||
| courseCode = courseCode.toUpperCase(); | ||
|
|
||
| // Query database | ||
| const result = await collection.findOne<CourseDetail | null>( | ||
| { | ||
| course_code: courseCode, | ||
| }, | ||
| { | ||
| projection: { | ||
| _id: 0, | ||
| }, | ||
| } | ||
| ); | ||
|
|
||
| return result; | ||
| } | ||
|
|
||
| /** | ||
| * Returns an array of course snippets in which course titles match the regex. | ||
| * Currently, only supports title matching; TODO: add description matching in the future. | ||
| * @param query regex | ||
| */ | ||
| export async function getCourseSnippetByRegex( | ||
| query: string | ||
| ): Promise<Array<CourseSnippet>> { | ||
| if (!query || query.trim().length <= 1) { | ||
| return []; | ||
| } | ||
|
|
||
| // Connect to Db and get collection | ||
| const db = await getDbInstance(); | ||
| const collection = db.collection("courses"); | ||
|
|
||
| // Build regex | ||
| const keywords: string[] = query.trim().split(" "); | ||
| const regexPreBuild = keywords.map((val) => "(.*" + val + ".*)+").join(""); | ||
| const regex = RegExp(regexPreBuild, "i"); | ||
|
|
||
| // Search | ||
| const result = collection | ||
| .aggregate([ | ||
| { | ||
| $match: { course_title: regex }, | ||
| }, | ||
| { | ||
| $project: { | ||
| _id: 0, | ||
| course_code: 1, | ||
| course_title: 1, | ||
| postgrad: 1, | ||
| }, | ||
| }, | ||
| ]) | ||
| .toArray(); | ||
|
|
||
| return result; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| { | ||
| "name": "api_v2", | ||
| "version": "1.0.0", | ||
| "main": "index.js", | ||
| "license": "MIT", | ||
| "scripts": { | ||
| "start": "ts-node-dev app.ts" | ||
| }, | ||
| "dependencies": { | ||
| "cors": "^2.8.5", | ||
| "express": "^4.17.1" | ||
| }, | ||
| "devDependencies": { | ||
| "@types/cors": "^2.8.7", | ||
| "@types/express": "^4.17.8" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| import { logger } from "../../../shared/logger"; | ||
| import { Router, Request, Response } from "express"; | ||
| import { | ||
| getCourseDetailByCourseCode, | ||
| getAllCourseSnippet, | ||
| getCourseSnippetByRegex, | ||
| } from "../../models/course"; | ||
|
|
||
| /** Router instance. */ | ||
| const courses = Router(); | ||
|
|
||
| courses.get("/course/all", async (req: Request, res: Response) => { | ||
| logger.info("Getting course list."); | ||
| // await connectToDb(); | ||
| logger.info("Connected to DB."); | ||
| // const course = new Course(); | ||
| const courseList = await getAllCourseSnippet(); | ||
| return res.json(courseList); | ||
| }); | ||
|
|
||
| courses.get("/course/search", async (req: Request, res: Response) => { | ||
| const { query } = req.query; | ||
| logger.info(`Searching for ${query}`); | ||
| const searchResult = await getCourseSnippetByRegex(query as string); | ||
| return res.json(searchResult); | ||
| }); | ||
|
|
||
| courses.get("/course/:course_code", async (req: Request, res: Response) => { | ||
| const courseCode = req.params.course_code.toUpperCase(); | ||
| logger.info(`Getting course detail for ${courseCode}`); | ||
| const courseDetail = await getCourseDetailByCourseCode(courseCode); | ||
| return res.json(courseDetail); | ||
| }); | ||
|
|
||
| export { courses }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| import { courses } from "./courses"; | ||
|
|
||
| export { courses }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| import * as winston from "winston"; | ||
|
|
||
| const logger = winston.createLogger({ | ||
| level: "info", | ||
| format: winston.format.json(), | ||
| defaultMeta: { service: "user-service" }, | ||
| transports: [ | ||
| // | ||
| // - Write to all logs with level `info` and below to `combined.log` | ||
| // - Write all logs error (and below) to `error.log`. | ||
| // | ||
| new winston.transports.File({ filename: "error.log", level: "error" }), | ||
| new winston.transports.File({ filename: "combined.log" }), | ||
| ], | ||
| }); | ||
|
|
||
| // | ||
| // If we're not in production then log to the `console` with the format: | ||
| // `${info.level}: ${info.message} JSON.stringify({ ...rest }) ` | ||
| // | ||
| if (process.env.NODE_ENV !== "production") { | ||
| logger.add( | ||
| new winston.transports.Console({ | ||
| format: winston.format.simple(), | ||
| }) | ||
| ); | ||
| } | ||
|
|
||
| export { logger }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
我感觉这里和上面的 /course/all 可以合并更符合REST的面向资源的思想
all API: /courses
query API: /course?q=xxx
getOne API: /courses/:courseID