Last active
May 6, 2022 14:56
-
-
Save felipeggrod/9b34e37e189c2f73cb508006a4ab9ee3 to your computer and use it in GitHub Desktop.
type-graphql + typeorm: local entity with a property that references an external entity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Field, ObjectType } from 'type-graphql'; | |
| import { GetHTTP } from '../utils/externalHttpAxiosHelper'; | |
| @ObjectType() | |
| export class Employment { | |
| @Field() | |
| title: string; | |
| @Field() | |
| key_skill: string; | |
| } | |
| @ObjectType({ description: 'Entity that is stored externally' }) //Graphql Decorator | |
| export class ExternalEntity { | |
| @Field() | |
| id!: String; | |
| @Field() | |
| name: String; | |
| @Field() | |
| email: String; | |
| @Field() | |
| username: String; | |
| @Field() | |
| employment: Employment; | |
| static async find(id: String) { | |
| var fakeUser = await GetHTTP('https://random-data-api.com/api/users/random_user'); | |
| // console.log('external user given id: ' + id); | |
| // console.log(fakeUser); | |
| return fakeUser; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Entity, Index, BaseEntity, Column, PrimaryColumn, BeforeInsert, DeleteDateColumn, CreateDateColumn, UpdateDateColumn, ManyToOne, JoinColumn, AfterLoad } from 'typeorm'; | |
| import { v4 as uuid } from 'uuid'; | |
| import { Field, ObjectType } from 'type-graphql'; | |
| import { ExternalEntity } from '../adapters/ExternalEntity'; | |
| @ObjectType({ description: 'Entity that is stored in the local DB' }) //Graphql Decorator | |
| @Entity() //Typeorm Decorator | |
| export class LocalEntity extends BaseEntity { | |
| constructor() { | |
| super(); | |
| this.id = uuid(); | |
| } | |
| @Field() | |
| @PrimaryColumn({ unique: true }) | |
| id!: String; | |
| //External entitiy | |
| @Column() | |
| externalEntityId: String; | |
| @Field(() => ExternalEntity) | |
| externalEntity: Promise<ExternalEntity>; | |
| @AfterLoad() | |
| async setExternal() { | |
| // All we gotta do is bind promises to any external field, and pass the locally stored id | |
| this.externalEntity = new Promise((resolve, reject) => resolve(ExternalEntity.find(this.externalEntityId))); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment