1

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

Vũ Anh Dũng
  • 980
  • 3
  • 13
  • 32
  • I'm not typescript master but shouldn't array also have type: `const users: User[] = [];` – baza92 Mar 30 '19 at 17:57
  • You can also check this module: https://github.com/ooesili/type-safe-json-decoder – baza92 Mar 30 '19 at 18:05
  • @baza92 Thanks for comment. But when I try to run function by ts-node, I get error when wrong format. But when I run server and request, it's not working. This issue is wrong property name it's still works. I think that module not handle the issue. Don't care to User[] because it's just visual DB – Vũ Anh Dũng Mar 30 '19 at 18:11

1 Answers1

1

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

Zobia Kanwal
  • 4,085
  • 4
  • 15
  • 38
baza92
  • 344
  • 1
  • 10
  • I don't know why type-safe-json-decoder installed but when I import it's I see Cannot find module :/ – Vũ Anh Dũng Mar 31 '19 at 10:36
  • But, the model have many properties. I also user Decoder to validate :/ – Vũ Anh Dũng Mar 31 '19 at 10:36
  • @VũAnhDũng I'm not fully understand. Can you share your code which is not working? "Cannot find module" indicates that you didn't install the module. – baza92 Mar 31 '19 at 11:15
  • I have been installed the module. I mean I will have to use Decoder for all apis, all attributes of models. – Vũ Anh Dũng Apr 01 '19 at 04:13
  • If you want to parse json to object in more automatic way there are some alternatives available - you can check this thread: https://stackoverflow.com/questions/22875636/how-do-i-cast-a-json-object-to-a-typescript-class – baza92 Apr 01 '19 at 05:47