Chicky
Chicky

Reputation: 1257

Express body request not match with model, but its still working?

My class model:

class User {
   userName: string;
   password: string;
}

My function handle:

const users = [];
function addUser(user: User) {
  users.push(user);
}

Express router:

router.post('/users', (req, res) => {
  addUser(req.body);
})

I want to request following userModel format. But when I request an object not following userModel format, addUser function still working and push a wrong object format to users[].

How I can throw error if req.body not match with userModel

Upvotes: 1

Views: 331

Answers (1)

baza92
baza92

Reputation: 344

I was able to implement desired behaviour using type-safe-json-decoder:

index.js

import express = require("express");
import bodyParser from "body-parser";
import { Decoder, object, string } from 'type-safe-json-decoder'

const app: express.Application = express();
app.use(bodyParser.json());

class User {
    constructor(userName: string, password: string) {
        this.userName = userName;
        this.password = password
    }
    userName: string;
    password: string;
}

const usersDecoder: Decoder<User> = object(
    ['userName', string()],
    ['password', string()],
    (userName, password) => ({ userName, password })
);

const users: User[] = [];
function addUser(user: User) {
    users.push(user);
    console.log(users);
}

app.post('/add', (req, res) => {
    const user: User = usersDecoder.decodeJSON(JSON.stringify(req.body))
    addUser(user);
    res.send("User added!");
});

app.listen(8080, () => console.log("Listening on 8080"));

package.json

{
  "name": "ts",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "tsc": "tsc"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/express": "^4.16.1",
    "body-parser": "^1.18.3",
    "express": "^4.16.4",
    "type-safe-json-decoder": "^0.2.0",
    "typescript": "^3.4.1"
  },
  "devDependencies": {
    "@types/body-parser": "^1.17.0"
  }
}

In order to run:

  1. npm install
  2. npm run tsc -- --init
  3. npm run tsc
  4. node index.js

When executing POST with proper JSON you should receive: User added!.

In case of incorrect JSON format an error should be thrown: error example

Upvotes: 1

Related Questions