Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding required methods and functions for "__typename must be const" change #137

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ case and compare the output to corresponding `.expected.ts` file. If the
output does not match the expected output, the test runner will fail.

The tests in `src/tests/fixtures` are unit tests that test the behavior of the
extraction. They extract GraphQL SDL from the file and write that as output.
extraction and code generation. They extract GraphQL SDL, generated `schema.ts` or any associated errors and code actions from the file and write that as output.

If the test includes a line like `// Locate: User.name` of `// Locate: SomeType`
then the test runner will instead locate the given entity and write the location
as output.

The tests in `src/tests/integrationFixtures` are integration tests that test the _runtime_ behavior of the tool. They expect each file to be a `.ts` file with `@gql` docblock tags which exports a root query class as the named export `Query` and a GraphQL query text under the named export `query`. The test runner will execute the query against the root query class and emit the returned response JSON as the test output.
The tests in `src/tests/integrationFixtures` are integration tests that test the _runtime_ behavior of the generated code. Each directory contains an `index.ts` file with `@gql` docblock tags which exports a root query class as the named export `Query` and a GraphQL query text under the named export `query`. The test runner will execute the query against the root query class and emit the returned response JSON as the test output.

```

Expand Down
2 changes: 1 addition & 1 deletion examples/express-graphql-http/models/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Group from "./Group";

/** @gqlType User */
export default class UserResolver implements IPerson {
__typename = "User";
__typename = "User" as const;
/** @gqlField */
name(): string {
return "Alice";
Expand Down
2 changes: 1 addition & 1 deletion examples/express-graphql/models/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Group from "./Group";

/** @gqlType User */
export default class UserResolver implements IPerson {
__typename = "User";
__typename = "User" as const;
/** @gqlField */
name(): string {
return "Alice";
Expand Down
2 changes: 1 addition & 1 deletion examples/next-js/app/api/graphql/models/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Group from "./Group";

/** @gqlType User */
export default class UserResolver implements IPerson {
__typename = "User";
__typename = "User" as const;
/** @gqlField */
name(): string {
return "Alice";
Expand Down
71 changes: 44 additions & 27 deletions examples/production-app/Database.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { PubSub } from "./PubSub";
import { VC } from "./ViewerContext";
import { Like } from "./models/Like";
import { Post } from "./models/Post";
import { User } from "./models/User";

/**
* This module is intended to represent a database.
Expand Down Expand Up @@ -92,101 +95,115 @@ export async function createPost(
title: string;
content: string;
},
): Promise<PostRow> {
): Promise<Post> {
vc.log(`DB query: createPost: ${JSON.stringify(draft)}`);
const id = (MOCK_POSTS.length + 1).toString();
const row = { id, ...draft, publishedAt: new Date() };
MOCK_POSTS.push(row);
return row;
return new Post(vc, row);
}

export async function selectPostsWhereAuthor(
vc: VC,
authorId: string,
): Promise<Array<PostRow>> {
): Promise<Array<Post>> {
vc.log(`DB query: selectPostsWhereAuthor: ${authorId}`);
return MOCK_POSTS.filter((post) => post.authorId === authorId);
return MOCK_POSTS.filter((post) => post.authorId === authorId).map((row) => {
return new Post(vc, row);
});
}

export async function getPostsByIds(
vc: VC,
ids: readonly string[],
): Promise<Array<PostRow>> {
): Promise<Array<Post>> {
vc.log(`DB query: getPostsByIds: ${ids.join(", ")}`);
return ids.map((id) => nullThrows(MOCK_POSTS.find((post) => post.id === id)));
return ids.map((id) => {
const row = nullThrows(MOCK_POSTS.find((post) => post.id === id));
return new Post(vc, row);
});
}

export async function selectUsers(vc: VC): Promise<Array<UserRow>> {
export async function selectUsers(vc: VC): Promise<Array<User>> {
vc.log("DB query: selectUsers");
return MOCK_USERS;
return MOCK_USERS.map((row) => new User(vc, row));
}

export async function createUser(
vc: VC,
draft: { name: string },
): Promise<UserRow> {
): Promise<User> {
vc.log(`DB query: createUser: ${JSON.stringify(draft)}`);
const id = (MOCK_POSTS.length + 1).toString();
const row = { id, ...draft };
MOCK_USERS.push(row);
return row;
return new User(vc, row);
}

export async function getUsersByIds(
vc: VC,
ids: readonly string[],
): Promise<Array<UserRow>> {
): Promise<Array<User>> {
vc.log(`DB query: getUsersByIds: ${ids.join(", ")}`);
return ids.map((id) => nullThrows(MOCK_USERS.find((user) => user.id === id)));
return ids.map((id) => {
const row = nullThrows(MOCK_USERS.find((user) => user.id === id));
return new User(vc, row);
});
}

export async function selectLikes(vc: VC): Promise<Array<LikeRow>> {
export async function selectLikes(vc: VC): Promise<Array<Like>> {
vc.log("DB query: selectLikes");
return MOCK_LIKES;
return MOCK_LIKES.map((row) => new Like(vc, row));
}

export async function createLike(
vc: VC,
like: { userId: string; postId: string },
): Promise<LikeRow> {
): Promise<Like> {
vc.log(`DB query: createLike: ${JSON.stringify(like)}`);
const id = (MOCK_LIKES.length + 1).toString();
const row = { ...like, id, createdAt: new Date() };
MOCK_LIKES.push(row);
PubSub.publish("postLiked", like.postId);
return row;
return new Like(vc, row);
}

export async function getLikesByIds(
vc: VC,
ids: readonly string[],
): Promise<Array<LikeRow>> {
): Promise<Array<Like>> {
vc.log(`DB query: getLikesByIds: ${ids.join(", ")}`);
return ids.map((id) => nullThrows(MOCK_LIKES.find((like) => like.id === id)));
return ids.map((id) => {
const row = nullThrows(MOCK_LIKES.find((like) => like.id === id));
return new Like(vc, row);
});
}

export async function getLikesByUserId(
vc: VC,
userId: string,
): Promise<Array<LikeRow>> {
): Promise<Array<Like>> {
vc.log(`DB query: getLikesByUserId: ${userId}`);
return MOCK_LIKES.filter((like) => like.userId === userId);
return MOCK_LIKES.filter((like) => like.userId === userId).map((row) => {
return new Like(vc, row);
});
}

export async function getLikesByPostId(
vc: VC,
postId: string,
): Promise<Array<LikeRow>> {
): Promise<Array<Like>> {
vc.log(`DB query: getLikesByPostId: ${postId}`);
return MOCK_LIKES.filter((like) => like.postId === postId);
return MOCK_LIKES.filter((like) => like.postId === postId).map((row) => {
return new Like(vc, row);
});
}

export async function getLikesForPost(
vc: VC,
postId: string,
): Promise<LikeRow[]> {
export async function getLikesForPost(vc: VC, postId: string): Promise<Like[]> {
vc.log(`DB query: getLikesForPost: ${postId}`);
return MOCK_LIKES.filter((like) => like.postId === postId);
return MOCK_LIKES.filter((like) => like.postId === postId).map((row) => {
return new Like(vc, row);
});
}

function nullThrows<T>(value: T | null | undefined): T {
Expand Down
4 changes: 2 additions & 2 deletions examples/production-app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ This example includes a relatively fully featured app to demonstrate how real-wo

## Implementation notes

Dataloaders are attached to the per-request viewer context. This enables per-request caching while avoiding the risk of leaking data between requests/users.
DataLoaders are attached to the per-request viewer context. This enables per-request caching while avoiding the risk of leaking data between requests/users.

The viewer context is passed all the way through the app to the data layer. This would enable permission checking to be defined as close to the data as possible.
The viewer context (VC) is passed all the way through the app to the data layer. This would enable permission checking to be defined as close to the data as possible. Additionally, the VC is stashed on each model instance, enabling the model create edges to other models without needing to get a new VC.

## Running the demo

Expand Down
25 changes: 11 additions & 14 deletions examples/production-app/ViewerContext.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
import DataLoader from "dataloader";
import {
LikeRow,
PostRow,
UserRow,
getPostsByIds,
getUsersByIds,
getLikesByIds,
} from "./Database";
import { getPostsByIds, getUsersByIds, getLikesByIds } from "./Database";
import { YogaInitialContext } from "graphql-yoga";
import { Post } from "./models/Post";
import { User } from "./models/User";
import { Like } from "./models/Like";

/**
* Viewer Context
Expand All @@ -20,22 +16,22 @@ import { YogaInitialContext } from "graphql-yoga";
* through the entire request.
*/
export class VC {
_postLoader: DataLoader<string, PostRow>;
_userLoader: DataLoader<string, UserRow>;
_likeLoader: DataLoader<string, LikeRow>;
_postLoader: DataLoader<string, Post>;
_userLoader: DataLoader<string, User>;
_likeLoader: DataLoader<string, Like>;
_logs: string[] = [];
constructor() {
this._postLoader = new DataLoader((ids) => getPostsByIds(this, ids));
this._userLoader = new DataLoader((ids) => getUsersByIds(this, ids));
this._likeLoader = new DataLoader((ids) => getLikesByIds(this, ids));
}
async getPostById(id: string): Promise<PostRow> {
async getPostById(id: string): Promise<Post> {
return this._postLoader.load(id);
}
async getUserById(id: string): Promise<UserRow> {
async getUserById(id: string): Promise<User> {
return this._userLoader.load(id);
}
async getLikeById(id: string): Promise<LikeRow> {
async getLikeById(id: string): Promise<Like> {
return this._likeLoader.load(id);
}
userId(): string {
Expand All @@ -49,4 +45,5 @@ export class VC {
}
}

/** @gqlContext */
export type Ctx = YogaInitialContext & { vc: VC };
9 changes: 3 additions & 6 deletions examples/production-app/graphql/Node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@ import { fromGlobalId, toGlobalId } from "graphql-relay";
import { ID } from "grats";
import { Query } from "./Roots";
import { Ctx } from "../ViewerContext";
import { User } from "../models/User";
import { Post } from "../models/Post";
import { Like } from "../models/Like";

/**
* Converts a globally unique ID into a local ID asserting
Expand Down Expand Up @@ -53,11 +50,11 @@ export async function node(
// source of bugs.
switch (type) {
case "User":
return new User(await ctx.vc.getUserById(id));
return ctx.vc.getUserById(id);
case "Post":
return new Post(await ctx.vc.getPostById(id));
return ctx.vc.getPostById(id);
case "Like":
return new Like(await ctx.vc.getLikeById(id));
return ctx.vc.getLikeById(id);
default:
throw new Error(`Unknown typename: ${type}`);
}
Expand Down
12 changes: 6 additions & 6 deletions examples/production-app/models/Like.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { Post } from "./Post";
* A reaction from a user indicating that they like a post.
* @gqlType */
export class Like extends Model<DB.LikeRow> implements GraphQLNode {
__typename = "Like";
__typename = "Like" as const;

/**
* The date and time at which the post was liked.
Expand All @@ -24,15 +24,15 @@ export class Like extends Model<DB.LikeRow> implements GraphQLNode {
/**
* The user who liked the post.
* @gqlField */
async liker(_args: unknown, ctx: Ctx): Promise<User> {
return new User(await ctx.vc.getUserById(this.row.userId));
async liker(): Promise<User> {
return this.vc.getUserById(this.row.userId);
}

/**
* The post that was liked.
* @gqlField */
async post(_args: unknown, ctx: Ctx): Promise<Post> {
return new Post(await ctx.vc.getPostById(this.row.postId));
async post(): Promise<Post> {
return this.vc.getPostById(this.row.postId);
}
}

Expand All @@ -59,5 +59,5 @@ export async function createLike(
): Promise<CreateLikePayload> {
const id = getLocalTypeAssert(args.input.postId, "Post");
await DB.createLike(ctx.vc, { ...args.input, userId: ctx.vc.userId() });
return { post: new Post(await ctx.vc.getPostById(id)) };
return { post: await ctx.vc.getPostById(id) };
}
9 changes: 3 additions & 6 deletions examples/production-app/models/LikeConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { Query, Subscription } from "../graphql/Roots";
import { Like } from "./Like";
import { PageInfo } from "../graphql/Connection";
import { connectionFromArray } from "graphql-relay";
import { Post } from "./Post";
import { PubSub } from "../PubSub";
import { filter, map, pipe } from "graphql-yoga";
import { getLocalTypeAssert } from "../graphql/Node";
Expand Down Expand Up @@ -53,8 +52,7 @@ export async function likes(
},
ctx: Ctx,
): Promise<LikeConnection> {
const rows = await DB.selectLikes(ctx.vc);
const likes = rows.map((row) => new Like(row));
const likes = await DB.selectLikes(ctx.vc);
return {
...connectionFromArray(likes, args),
count: likes.length,
Expand All @@ -71,11 +69,10 @@ export async function postLikes(
ctx: Ctx,
): Promise<AsyncIterable<LikeConnection>> {
const id = getLocalTypeAssert(args.postID, "Post");
const postRow = await ctx.vc.getPostById(id);
const post = new Post(postRow);
const post = await ctx.vc.getPostById(id);
return pipe(
PubSub.subscribe("postLiked"),
filter((postId) => postId === id),
map(() => post.likes({}, ctx)),
map(() => post.likes({})),
);
}
4 changes: 3 additions & 1 deletion examples/production-app/models/Model.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { VC } from "../ViewerContext";

/**
* Generic model class built around a database row
*/
export abstract class Model<R extends { id: string }> {
constructor(protected row: R) {}
constructor(protected vc: VC, protected row: R) {}
localID(): string {
return this.row.id;
}
Expand Down
Loading