How to initialize an entity passing in an object using typeorm

Viewed 16086

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?

3 Answers

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);

Edit: I did arrive at this thread by trying to search how to initialize a TypeORM object/class by passing attributes/body params/object. So, if you need a single object you can use the manager.

import { getManager } from "typeorm";
// ...
const manager = getManager();
const newUser = manager.create(User, req.body);
const user = await manager.save(newUser);

Example creating a user object and saving it from an express request dynamic body. This example is just to illustrate. Validate and sanitize your schema before passing it to the create function to avoid allowing the API user to pass any parameter like {admin: true} ;).

import { getManager } from "typeorm";
createConnection()
  .then(async (connection) => {
    const app = express();
    app.use(express.json());

    app.post("/users", async (req: Request, res: Response) => {
      const manager = getManager();
      const newUser = manager.create(User, req.body);
      const user = await manager.save(newUser);
      res.json(user);
    });

    app.listen(4000);
  })
  .catch((error) => console.log(error));

I just want to add to @Kay's answer. If you're using Active Records pattern by extending BaseEntity class from typeorm, you can directly call create method on your entity, assuming List is the entity, like

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