From 3b6c71dd4477d28327305c0add7874097dbcb7f3 Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Thu, 8 Sep 2022 11:23:03 -0500 Subject: [PATCH] Lookup individual nodes from anywhere. We need to be able to lookup a node from anywhere in a hierarchy so that it can be loaded lazily. This adds a `get()` method onto the return value of `factory.all()` to find the node. It can also be used for implementing the Relay `node {}` query. --- src/graphql/graphgen.ts | 16 ++++++++++++++-- test/graphql.test.ts | 5 +++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/graphql/graphgen.ts b/src/graphql/graphgen.ts index 8116a58..1bef271 100644 --- a/src/graphql/graphgen.ts +++ b/src/graphql/graphgen.ts @@ -32,13 +32,17 @@ export interface GraphGen> { typename: T, preset?: Preset, ): Node & API[T]; - all(typename: T): Iterable; + all(typename: T): Collection; createMany( typename: T, amount: number, ): Iterable; } +export interface Collection extends Iterable { + get(id: string): T | undefined; +} + export interface Generate { (info: GenerateInfo): unknown; } @@ -274,13 +278,21 @@ directive @computed on FIELD_DEFINITION return transformed; } - function all(typename: T) { + function all( + typename: T, + ): Collection { return { *[Symbol.iterator]() { for (let id in graph.roots[typename]) { yield toNode(graph.roots[typename][id]); } }, + get(id) { + let vertex = graph.roots[typename][Number(id)]; + if (vertex) { + return toNode(vertex); + } + }, }; } diff --git a/test/graphql.test.ts b/test/graphql.test.ts index eb9e138..2493699 100644 --- a/test/graphql.test.ts +++ b/test/graphql.test.ts @@ -47,6 +47,11 @@ describe("using graphql", () => { expect(all).toHaveLength(3); }); + it("can lookup a single node by type and id", () => { + let person = graphgen.create("Person"); + expect(graphgen.all("Person").get(person.id)).toBe(person); + }); + it("assigns an id and corresponding typename to each node", () => { let person = graphgen.create("Person"); expect(person.id).toBe("1");