Skip to content

Instantly share code, notes, and snippets.

@felipeggrod
Last active May 6, 2022 14:56
Show Gist options
  • Select an option

  • Save felipeggrod/9b34e37e189c2f73cb508006a4ab9ee3 to your computer and use it in GitHub Desktop.

Select an option

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