最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeORM return plain object - Stack Overflow

programmeradmin6浏览0评论

How do I return a plain JavaScript object from TypeORM Repository functions like find, create, update or delete?

const user = User.findOne({ where: { id: 1 } }); 

Actual:

User | undefined

{
  User: {
    id: 1
  }
}

Instead I would like to receive a plain object independent from any library / framework

Expected:

{
  id: 1
}

This way it would be easier to be framework independent and your repository calls could be interchangeable at any point of time without rewriting the entire application and not to depend on third party scripts that heavily.

Sequelize for example has an option { plain: true }

How do I return a plain JavaScript object from TypeORM Repository functions like find, create, update or delete?

const user = User.findOne({ where: { id: 1 } }); 

Actual:

User | undefined

{
  User: {
    id: 1
  }
}

Instead I would like to receive a plain object independent from any library / framework

Expected:

{
  id: 1
}

This way it would be easier to be framework independent and your repository calls could be interchangeable at any point of time without rewriting the entire application and not to depend on third party scripts that heavily.

Sequelize for example has an option { plain: true }

Share Improve this question asked Nov 18, 2019 at 21:04 marcobiedermannmarcobiedermann 4,9435 gold badges28 silver badges39 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

You can easily use the class-transformer library to produce plain objects from entity instances:

https://github./typestack/class-transformer

const user = repository.findOne({ where: { id: 1 } });
const plain = classToPlain(user);

Another way is to use queryBuilder API and returns raw results from the database

const rawResult = repository.createQueryBuilder("user")
    .select("user")
    .where("user.id = :id", {id: 1})
    .getRawOne();

The point is why would you want to do so? Entity is first citizen in TypeOrm so you want that any change on its structure should generate pile errors if something is not back patible. Using plain objects would hide contract changes, and you would discover errors only at runtime, not sure if it is an optimal way to work with TypeOrm to my mind.

Without class-transformer it is actually quite easy to create a simple method like this:

entityToObject<T>(entity: T): T {
    return Object.assign({}, entity);
}

than use it on findOne returned object like so:

async view_user(id: number): Promise<User|null> {
    const user = await this.repository.findOne({where: {id}});
    if(!user) {
        throw Error("User not found");
    }
    return this.entityToObject<User>(user);
}
entityToObject<T>(entity: T): T {
    return Object.assign({}, entity);
}
发布评论

评论列表(0)

  1. 暂无评论