Home > Back-end >  Store postman body JSON properties inside Typescript class with multiple optional properties
Store postman body JSON properties inside Typescript class with multiple optional properties

Time:07-19

I am developing an API which I am calling from Postman. The POST request body looks like this:-

{
    "name": "John",
    "username": "john123"
}

I am storing this request body in a constant which is of type MyRequest:-

const myRequest = new MyRequest(req.body);

where MyRequest is a Typescript class:-

export default class MyRequest {
    public name: string;
    public username: string;

    constructor(data: any) {
        this.name = data.name;
        this.username = data.username;
    }
}

Now my requirement is, there can be multiple optional and unknown JSON body parameters in the Postman request, like so:-

{
    "name": "John",
    "username": "john123",
    "age": 10,
    "address": "somewhere",
    "some_new_key": "some_new_value",
    .
    .
    .
    .
    "another_new_key": "another_new_value"
}

I need to store all of these values in MyRequest, where only name and username is mandatory, and all other fields are optional, and then initialize them in the constructor. How do I write the MyRequest class?

CodePudding user response:

You can add properties to the class dynamically by adding them to the this instance inside the constructor method.

interface MyRequestInterface {
  name: string;
  username: string;
  [key: string]: string | number ;
}

class MyRequest {
    public name: string;
    public username: string;
    [key: string]: string | number ;

    constructor(data: MyRequestInterface) {
        this.name = data.name;
        this.username = data.username;
        Object.keys(data).forEach((e) => {
          this[e] = data[e];
        })
    }
}

const data: MyRequestInterface = {
    name: "John",
    username: "john123",
    age: 10,
    address: "somewhere",
    some_new_key: "some_new_value",
    another_new_key: "another_new_value"
}

const request = new MyRequest(data)

console.log(request.name)
  • Related