Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript : convert post request body to map

I'm programming an rest api with node js and typescript and for create user, my api recieve a json post :

import {Request, Response, Router} from "express";
import {User} from '../../../models/user.model';
import {createUser} from '../../../factories/user.factory';

export default [
        {
            path: "/api/v1/user/create",
            method: "post",
            handler: [
                async (req: Request, res: Response) => {
                    createUser(new User(req.body.user));
                    res.status(200).send(req.body);
                }
            ]
        }
    ];

For exemple, I send that :

{
    "user": {
        "email": "[email protected]",
        "password": "12345678",
        "firstName": "Jérémy"
        }
    }

I would like create an object "User" with the object req.body.user :

import {Timestamp} from './timestamp.model';

export class User {
    id: bigint | undefined;
    email: string | undefined;
    password: string | undefined;
    firstName: string | undefined;
    lastName: string | undefined;
    pseudo: string | undefined;
    birthDate: Timestamp | undefined;
    lastEditDate: Timestamp | undefined;
    creationDate: Timestamp | undefined;
    googleAuthToken: string | undefined;
    language: string | undefined;
    profileAvatarUrl: string | undefined;
    profileBannerUrl: string | undefined;
    primaryLightColor: string | undefined;
    secondaryLightColor: string | undefined;
    primaryDarkColor: string | undefined;
    secondaryDarkColor: string | undefined;

    constructor(array: object) {
        console.log(array);
        // @ts-ignore
        console.log(array.gg);
        // @ts-ignore
        this.id = array.id;
        // @ts-ignore
        this.email = array.email;
        // @ts-ignore
        this.password = array.password;
        // @ts-ignore
        this.firstName = array.firstName;
        // @ts-ignore
        this.lastName = array.lastName;
        // @ts-ignore
        this.pseudo = array.pseudo;
        // @ts-ignore
        this.birthDate = array.birthDate;
        // @ts-ignore
        this.lastEditDate = array.lastEditDate;
        // @ts-ignore
        this.creationDate = array.creationDate;
        // @ts-ignore
        this.googleAuthToken = array.googleAuthToken;
        // @ts-ignore
        this.language = array.language;
        // @ts-ignore
        this.profileAvatarUrl = array.profileAvatarUrl;
        // @ts-ignore
        this.profileBannerUrl = array.profileBannerUrl;
        // @ts-ignore
        this.primaryLightColor = array.primaryLightColor;
        // @ts-ignore
        this.secondaryLightColor = array.secondaryLightColor;
        // @ts-ignore
        this.primaryDarkColor = array.primaryDarkColor;
        // @ts-ignore
        this.secondaryDarkColor = array.secondaryDarkColor;
        // @ts-ignore
    }

     toMap() {
        return {
            "id": this.id,
            "email": this.email,
            "firstName": this.firstName,
            "lastName": this.lastName,
            "pseudo": this.pseudo,
            "profileAvatarUrl": this.profileAvatarUrl,
            "birthDate": this.birthDate,
            "lastEditDate": this.lastEditDate,
            "creationDate": this.creationDate,
            "language": this.language,
            "googleAuthToken": this.googleAuthToken,
            "profileBannerUrl": this.profileBannerUrl,
            "primaryLightColor": this.primaryLightColor,
            "secondaryLightColor": this.secondaryLightColor,
            "primaryDarkColor": this.primaryDarkColor,
            "secondaryDarkColor": this.secondaryDarkColor,
        }
    }

}

I have put all this "// @ts-ignore" because if not , I've this error :

src/models/user.model.ts(27,25): error TS2339: Property 'id' does not exist on type 'object'. src/models/user.model.ts(28,32): error TS2339: Property 'email' does not exist on type 'object'. src/models/user.model.ts(29,35): error TS2339: Property 'password' does not exist on type 'object'. src/models/user.model.ts(30,36): error TS2339: Property 'firstName' does not exist on type 'object'. src/models/user.model.ts(31,35): error TS2339: Property 'lastName' does not exist on type 'object'.

My question is : How correctly make my class user for not have to put all this "// @ts-ignore" ?

Thank's in advance. Jérémy.

like image 420
Jérémy Gachon Avatar asked Apr 22 '26 07:04

Jérémy Gachon


2 Answers

I have a different suggestion which I find nice in typescript and started using intensively. Instead of creating a class for your user you can define it as an interface.

export interface User { 
 email: string, 
 password: string, 
 firstName: string,
 lastName: string, 
 // etc 
}

and then simply do:

const user = req.body.user as User; 

It's faster and cleaner to type as long as you use these just for creating domain model objects with no business logic.

EDIT:

IF you need to stick with class then try using any type.

 export class user { 
 constructor(userDto: any) { 
   // your logic
   } 
 }


 new User(req.body.user); 
like image 108
Dan Dinu Avatar answered Apr 24 '26 23:04

Dan Dinu


I'm particularly likes Dan's solution, is clean and also is fast. But if he ToMap function is need it, you can consider use https://lodash.com/ is a very handy library, helps with arrays, object mappings, deep cloning .

Regards

PD: you also can use indexer secondaryDarkColor =array.['secondaryDarkColor']

like image 36
Agustin Eloy Barrios Avatar answered Apr 24 '26 23:04

Agustin Eloy Barrios



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!