Merge branch 'master' into node-errorhandling
This commit is contained in:
118
nodejs/middleware/app.ts
Normal file
118
nodejs/middleware/app.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import express, { Request, Response, NextFunction } from 'express'
|
||||
import morgan from 'morgan'
|
||||
|
||||
const app = express()
|
||||
const port:number = 3000
|
||||
|
||||
|
||||
interface Product {
|
||||
|
||||
name: string
|
||||
price: number
|
||||
brand: string
|
||||
category?: string
|
||||
}
|
||||
|
||||
interface ProductCreationResponse {
|
||||
productID: string
|
||||
result: string
|
||||
}
|
||||
|
||||
|
||||
class AppError extends Error{
|
||||
statusCode: number;
|
||||
|
||||
constructor(statusCode: number, message: string) {
|
||||
super(message);
|
||||
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
this.name = Error.name;
|
||||
this.statusCode = statusCode;
|
||||
Error.captureStackTrace(this);
|
||||
}
|
||||
}
|
||||
|
||||
const requestLogger = (request: Request, response: Response, next: NextFunction) => {
|
||||
console.log(`${request.method} url:: ${request.url}`);
|
||||
next()
|
||||
}
|
||||
|
||||
app.use(express.static('images'))
|
||||
app.use(express.static('htmls'))
|
||||
app.use(requestLogger)
|
||||
|
||||
app.use(morgan('tiny'))
|
||||
|
||||
app.use('/products', express.json({ limit: 100 }))
|
||||
|
||||
// Error handling Middleware functions
|
||||
const errorLogger = (error: Error, request: Request, response: Response, next: NextFunction) => {
|
||||
console.log( `error ${error.message}`)
|
||||
next(error) // calling next middleware
|
||||
}
|
||||
|
||||
const errorResponder = (error: AppError, request: Request, response: Response, next: NextFunction) => {
|
||||
response.header("Content-Type", 'application/json')
|
||||
|
||||
const status = error.statusCode || 400
|
||||
response.status(status).send(error.message)
|
||||
}
|
||||
const invalidPathHandler = (request: Request, response: Response, next: NextFunction) => {
|
||||
response.status(400)
|
||||
response.send('invalid path')
|
||||
}
|
||||
|
||||
|
||||
|
||||
app.get('product', (request: Request, response: Response)=>{
|
||||
response.sendFile("productsample.html")
|
||||
})
|
||||
|
||||
// handle get request for path /
|
||||
app.get('/', (request: Request, response: Response) => {
|
||||
response.send('response for GET request');
|
||||
})
|
||||
|
||||
|
||||
const requireJsonContent = (request: Request, response: Response, next: NextFunction) => {
|
||||
if (request.headers['content-type'] !== 'application/json') {
|
||||
response.status(400).send('Server requires application/json')
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const addProducts = (request: Request, response: Response, next: NextFunction) => {
|
||||
let products: Product[] = []
|
||||
|
||||
const name: string = request.body.name
|
||||
|
||||
const brand: string = request.body.brand
|
||||
|
||||
const category: string = request.body.category
|
||||
|
||||
console.log(name + " " + brand)
|
||||
|
||||
products.push({name: request.body.name, brand: request.body.brand, price: request.body.price})
|
||||
|
||||
const productCreationResponse: ProductCreationResponse = {productID: "12345", result: "success"}
|
||||
response.json(productCreationResponse)
|
||||
|
||||
response.status(200).json(products);
|
||||
}
|
||||
app.post('/products', addProducts)
|
||||
|
||||
app.get('/productswitherror', (request: Request, response: Response) => {
|
||||
let error: AppError = new AppError(400, `processing error in request at ${request.url}`)
|
||||
|
||||
throw error
|
||||
})
|
||||
|
||||
app.use(errorLogger)
|
||||
app.use(errorResponder)
|
||||
app.use(invalidPathHandler)
|
||||
|
||||
app.listen(port, () => {
|
||||
console.log(`Server listening at port ${port}.`)
|
||||
})
|
||||
6
nodejs/middleware/htmls/productsample.html
Normal file
6
nodejs/middleware/htmls/productsample.html
Normal file
@@ -0,0 +1,6 @@
|
||||
<html>
|
||||
<body>
|
||||
<h2>My sample product page</h2>
|
||||
<img src="sample.jpg" alt="sample"></img>
|
||||
</body>
|
||||
</html>
|
||||
BIN
nodejs/middleware/images/sample.jpg
Normal file
BIN
nodejs/middleware/images/sample.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 7.3 KiB |
89
nodejs/middleware/index.js
Normal file
89
nodejs/middleware/index.js
Normal file
@@ -0,0 +1,89 @@
|
||||
const express = require('express')
|
||||
const morgan = require('morgan')
|
||||
|
||||
const app = express();
|
||||
|
||||
|
||||
const requestLogger = (request, response, next) => {
|
||||
console.log(`${request.method} url:: ${request.url}`);
|
||||
next()
|
||||
}
|
||||
|
||||
app.use(express.static('images'))
|
||||
app.use(express.static('htmls'))
|
||||
|
||||
app.use(requestLogger)
|
||||
|
||||
app.use(morgan('tiny'))
|
||||
|
||||
app.use('/products', express.json({ limit: 100 }))
|
||||
|
||||
// Error handling Middleware functions
|
||||
const errorLogger = (error, request, response, next) => {
|
||||
console.log( `error ${error.message}`)
|
||||
next(error) // calling next middleware
|
||||
}
|
||||
|
||||
const errorResponder = (error, request, response, next) => {
|
||||
response.header("Content-Type", 'application/json')
|
||||
|
||||
const status = error.status || 400
|
||||
response.status(status).send(error.message)
|
||||
}
|
||||
const invalidPathHandler = (request, response, next) => {
|
||||
response.status(400)
|
||||
response.send('invalid path')
|
||||
}
|
||||
|
||||
|
||||
|
||||
app.get('product', (request, response)=>{
|
||||
response.sendFile("productsample.html")
|
||||
})
|
||||
|
||||
// handle get request for path /
|
||||
app.get('/', (request, response) => {
|
||||
response.send('response for GET request');
|
||||
})
|
||||
|
||||
|
||||
const requireJsonContent = (request, response, next) => {
|
||||
if (request.headers['content-type'] !== 'application/json') {
|
||||
response.status(400).send('Server requires application/json')
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
}
|
||||
|
||||
// handle post request for path /products
|
||||
app.post('/products', requireJsonContent, (request, response) => {
|
||||
const products = []
|
||||
|
||||
const name = request.body.name
|
||||
|
||||
const brand = request.body.brand
|
||||
|
||||
const category = request.body.category
|
||||
|
||||
console.log(name + " " + brand)
|
||||
|
||||
products.push({name: request.body.name, brand: request.body.brand, price: request.body.price})
|
||||
|
||||
const productCreationResponse = {productID: "12345", result: "success"}
|
||||
response.json(productCreationResponse)
|
||||
})
|
||||
|
||||
app.get('/productswitherror', (request, response) => {
|
||||
let error = new Error(`processing error in request at ${request.url}`)
|
||||
error.statusCode = 400
|
||||
throw error
|
||||
})
|
||||
|
||||
app.use(errorLogger)
|
||||
app.use(errorResponder)
|
||||
app.use(invalidPathHandler)
|
||||
|
||||
const port = 3000
|
||||
app.listen(3000,
|
||||
() => console.log(`Server listening on port ${port}.`));
|
||||
|
||||
1399
nodejs/middleware/package-lock.json
generated
Normal file
1399
nodejs/middleware/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
22
nodejs/middleware/package.json
Normal file
22
nodejs/middleware/package.json
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "storefront1",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"express": "^4.17.3",
|
||||
"morgan": "^1.10.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "^4.17.13",
|
||||
"@types/node": "^17.0.21",
|
||||
"ts-node": "^10.7.0",
|
||||
"typescript": "^4.6.2"
|
||||
}
|
||||
}
|
||||
8
nodejs/middleware/tsconfig.json
Normal file
8
nodejs/middleware/tsconfig.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"target": "es6",
|
||||
"rootDir": "./",
|
||||
"esModuleInterop": true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user