Skip to content

Commit

Permalink
Merge pull request #35 from thefrontside/cl/lookup-individual-node
Browse files Browse the repository at this point in the history
Lookup individual nodes from anywhere.
  • Loading branch information
cowboyd authored Sep 8, 2022
2 parents 5ca9bb5 + 3b6c71d commit f454021
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/graphql/graphgen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,17 @@ export interface GraphGen<API = Record<string, any>> {
typename: T,
preset?: Preset<API[T]>,
): Node & API[T];
all<T extends string & keyof API>(typename: T): Iterable<Node & API[T]>;
all<T extends string & keyof API>(typename: T): Collection<Node & API[T]>;
createMany<T extends string & keyof API>(
typename: T,
amount: number,
): Iterable<Node & API[T]>;
}

export interface Collection<T> extends Iterable<T> {
get(id: string): T | undefined;
}

export interface Generate {
(info: GenerateInfo): unknown;
}
Expand Down Expand Up @@ -274,13 +278,21 @@ directive @computed on FIELD_DEFINITION
return transformed;
}

function all<T extends string & keyof API>(typename: T) {
function all<T extends string & keyof API>(
typename: T,
): Collection<Node & API[T]> {
return {
*[Symbol.iterator]() {
for (let id in graph.roots[typename]) {
yield toNode<API[typeof typename]>(graph.roots[typename][id]);
}
},
get(id) {
let vertex = graph.roots[typename][Number(id)];
if (vertex) {
return toNode(vertex);
}
},
};
}

Expand Down
5 changes: 5 additions & 0 deletions test/graphql.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down

0 comments on commit f454021

Please sign in to comment.