Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SCSE-227] Init merch nodejs app in monorepo #61

Merged
merged 3 commits into from
Feb 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions apps/merch/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Merch Backend Service

// todo
26 changes: 26 additions & 0 deletions apps/merch/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "merch",
"description": "NTU SCSE Merch Backend",
"version": "0.1.0",
"main": "dist/server.js",
"license": "Apache-2.0",
"scripts": {
"dev": "nodemon src/server.ts"
},
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"@types/cookie-parser": "^1.4.3",
"@types/express": "^4.17.9",
"@types/morgan": "^1.9.4",
"cookie-parser": "^1.4.6",
"morgan": "^1.10.0",
"nodelogger": "*",
"nodemon": "^2.0.6",
"ts-node": "^9.1.1",
"tsconfig": "*",
"typescript": "^4.8.4",
"winston": "^3.8.2"
}
}
9 changes: 9 additions & 0 deletions apps/merch/src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Router } from "express"

const router = Router()

router.get("/", (req, res) => {
res.json({ content: "Hello World" });
})

export default router
24 changes: 24 additions & 0 deletions apps/merch/src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import express from "express"
import path from 'path'
import cookieParser from 'cookie-parser'
import { nodeloggerMiddleware, Logger } from "nodelogger";

// import routers
import indexRouter from './routes/index'
// import usersRouter from './routes/users'

const app = express();

// middleware
app.use(nodeloggerMiddleware);
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
// app.use('/users', usersRouter);

app.listen("3000", ()=> Logger.info("server started on port 3000"))

export default app
26 changes: 26 additions & 0 deletions apps/merch/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"extends": "tsconfig/node.json",
"compilerOptions": {
"target": "es5",
"lib": [
"esnext"
],
"allowJs": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "./dist",
"rootDir": "./src",
"allowSyntheticDefaultImports": true
},
"include": [
"src"
],
"exclude": [
"node_modules",
"dist",
"build",
],
"ts-node": {
"transpileOnly": true
},
}
44 changes: 44 additions & 0 deletions packages/nodelogger/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# nodelogger

This package allows for easy console logging of nodejs applications.

## Setup

Add the following to your app's package.json:
```json5
{
"dependencies": {
// ...
"nodelogger": "*"
// ...
}
}
```

Add the nodelogger middleware to ur express app:

```typescript
// server.js

import { nodeloggerMiddleware } from "nodelogger"

...

app.use(morganMiddleware)

```

## Usage

```typescript
import { Logger } from "nodelogger"

// ...

Logger.error("Hello World")
Logger.warn("Hello World")
Logger.info("Hello World")
Logger.http("Hello World")
Logger.debug("Hello World")

```
4 changes: 4 additions & 0 deletions packages/nodelogger/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import nodeloggerMiddleware from "./lib/morganMiddleware";
import { Logger } from "./lib/winstonLogger"

export { Logger, nodeloggerMiddleware };
34 changes: 34 additions & 0 deletions packages/nodelogger/lib/morganMiddleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import morgan, { StreamOptions } from "morgan";

import { IncomingMessage } from "http";

import { Logger } from "./winstonLogger";

interface Request extends IncomingMessage {
body: {
query: string;
};
}

const stream: StreamOptions = {
write: (message) =>
Logger.http(message.substring(0, message.lastIndexOf("\n"))),
};

const skip = () => {
const env = process.env.NODE_ENV || "development";
return env !== "development";
};

const registerGraphQLToken = () => {
morgan.token("graphql-query", (req: Request) => `GraphQL ${req.body.query}`);
};

registerGraphQLToken();

const morganMiddleware = morgan(
":method :url :status :res[content-length] - :response-time ms\n:graphql-query",
{ stream, skip }
);

export default morganMiddleware;
76 changes: 76 additions & 0 deletions packages/nodelogger/lib/winstonLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import winston from "winston";

// Define your severity levels.
// With them, You can create log files,
// see or hide levels based on the running ENV.
const levels = {
error: 0,
warn: 1,
info: 2,
http: 3,
debug: 4,
};

// This method set the current severity based on
// the current NODE_ENV: show all the log levels
// if the server was run in development mode; otherwise,
// if it was run in production, show only warn and error messages.
const level = () => {
const env = process.env.NODE_ENV || "development";
const isDevelopment = env === "development";
return isDevelopment ? "debug" : "warn";
};

// Define different colors for each level.
// Colors make the log message more visible,
// adding the ability to focus or ignore messages.
const colors = {
error: "red",
warn: "yellow",
info: "blue",
http: "magenta",
debug: "white",
};

// Tell winston that you want to link the colors
// defined above to the severity levels.
winston.addColors(colors);

// Chose the aspect of your log customizing the log format.
const format = winston.format.combine(
// Add the message timestamp with the preferred format
winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss:ms" }),
// Tell Winston that the logs must be colored
winston.format.colorize({ all: true }),
// Define the format of the message showing the timestamp, the level and the message
winston.format.printf(
(info) =>
`${info.timestamp as string} ${info.level}: ${info.message as string}`
)
);

// Define which transports the logger must use to print out messages.
// In this example, we are using three different transports
const transports = [
// Allow the use the console to print the messages
new winston.transports.Console(),
// Allow to print all the error level messages inside the error.log file
// new winston.transports.File({
// filename: 'logs/error.log',
// level: 'error',
// }),
// Allow to print all the error message inside the all.log file
// (also the error log that are also printed inside the error.log(
// new winston.transports.File({ filename: 'logs/all.log' }),
];

// Create the logger instance that has to be exported
// and used to log messages.
const Logger = winston.createLogger({
level: level(),
levels,
format,
transports,
});

export { Logger };
18 changes: 18 additions & 0 deletions packages/nodelogger/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "nodelogger",
"version": "0.0.1",
"main": "index.ts",
"types": "index.ts",
"license": "Apache-2.0",
"scripts": {
"lint": "TIMING=1 eslint \"**/*.ts*\"",
"lint:fix": "TIMING=1 eslint --fix \"**/*.ts*\""
},
"dependencies": {
"@types/morgan": "^1.9.4",
"@types/winston": "^2.4.4",
"morgan": "^1.10.0",
"winston": "^3.8.2"
},
"devDependencies": {}
}
13 changes: 13 additions & 0 deletions packages/nodelogger/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"extends": "tsconfig/node.json",
"include": [
"**/*.js",
"**/*.ts",
],
"exclude": [
"dist",
"build",
"node_modules",
".turbo"
]
}
6 changes: 4 additions & 2 deletions turbo.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"MONGODB_URI",
"WORDPRESS_API_URL",
"PAYLOAD_PUBLIC_SERVER_URL",
"PAYLOAD_PUBLIC_SERVER_PORT"
"PAYLOAD_PUBLIC_SERVER_PORT",
"NODE_ENV"
]
},
"build": {
Expand All @@ -18,7 +19,8 @@
"MONGODB_URI",
"WORDPRESS_API_URL",
"PAYLOAD_PUBLIC_SERVER_URL",
"PAYLOAD_PUBLIC_SERVER_PORT"
"PAYLOAD_PUBLIC_SERVER_PORT",
"NODE_ENV"
],
"outputs": ["dist/**", "build/**", "out/**", ".next/**"]
},
Expand Down
Loading