Search code examples
node.jstypescripttypeorm

How to initialize an entity passing in an object using typeorm


I have an entity "List" and i want to create a new list by passing in an object into the constructor.

List.ts

import {Entity, PrimaryColumn, Column, CreateDateColumn, UpdateDateColumn, DeleteDateColumn } from "typeorm";

@Entity()
export class List {

    @PrimaryColumn()
    id: string;

    @Column({type: "varchar", nullable: true})
    dtype: string;

    @Column({type: "varchar", nullable: true})
    title: string;

    @Column({type: "varchar"})
    user_id: string;

    @Column({type: "varchar", nullable: true})
    brand_id: string;

    @CreateDateColumn({type: "timestamp", nullable: true})
    created_at: string;

    @UpdateDateColumn({type: "timestamp", nullable: true})
    updated_at: string;

    @DeleteDateColumn({type: "timestamp", nullable: true})
    deleted_at: string;

}

list.test

import "reflect-metadata";
import {createConnection, getRepository} from "typeorm";
import {List} from "./../../src/entity/lists/List";

describe("List", () => {

    let connection
    beforeAll( async () => {
        connection = await createConnection();
        console.log(connection);
    });

    it("should insert a list into database", async () => {

        const listRepository = getRepository(List);

        const list = new List({
            id: "7e60c4ef",
            dtype: "brandlist",
            title: "OnePlus",
            user_id: "3aecd1b0-c34d-4427-9abd-fdacef00eaa5",
            brand_id: "7e60c4ef-0e6f-46c9-948b-a97d555bf4e4",
        });

    })

})

Right now i get the following

Expected 0 arguments, but got 1.ts(2554)

Is there a way typeorm can automatically handles this?


Solution

  • There are two ways to solve this, the first is to declare your own constructor in the List class and assign the values but it gets messy.

    The preferred method is by using repository.create to create an instance of the entity from an object. https://github.com/typeorm/typeorm/blob/master/docs/repository-api.md

            const listRepository = connection.getRepository(List);
    
            const list = listRepository.create({
                id: "7e60c4ef",
                dtype: "brandlist",
                title: "OnePlus",
                user_id: "3aecd1b0-c34d-4427-9abd-fdacef00eaa5",
                brand_id: "7e60c4ef-0e6f-46c9-948b-a97d555bf4e4",
            });
    
            const newList = await listRepository.save(list);