@alxia/create 0.1.7 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +80 -25
  2. package/dist/args.d.ts +3 -1
  3. package/dist/args.d.ts.map +1 -1
  4. package/dist/index.js +19 -9
  5. package/dist/index.js.map +7 -7
  6. package/dist/main.d.ts +1 -1
  7. package/dist/main.d.ts.map +1 -1
  8. package/dist/registry.d.ts +2 -0
  9. package/dist/registry.d.ts.map +1 -1
  10. package/dist/versions.d.ts +5 -2
  11. package/dist/versions.d.ts.map +1 -1
  12. package/docs/README.md +16 -6
  13. package/docs/guide.md +428 -47
  14. package/docs/roadmap.md +24 -0
  15. package/docs/troubleshooting.md +152 -9
  16. package/package.json +16 -5
  17. package/templates/api/.env.example +9 -1
  18. package/templates/api/README.md +40 -12
  19. package/templates/api/openapi.yaml +13 -9
  20. package/templates/api/package.json +5 -3
  21. package/templates/api/src/app.spec.ts +42 -28
  22. package/templates/api/src/app.ts +13 -3
  23. package/templates/api/src/context.ts +3 -4
  24. package/templates/api/src/env.ts +20 -0
  25. package/templates/api/src/generated/alxia.ts +3 -3
  26. package/templates/api/src/generated/operations.ts +3 -3
  27. package/templates/api/src/generated/paths.ts +6 -6
  28. package/templates/api/src/generated/types.ts +14 -10
  29. package/templates/api/src/generated/zod.ts +6 -2
  30. package/templates/api/src/routes/todos.ts +2 -2
  31. package/templates/api/src/server.ts +8 -16
  32. package/templates/graphql/.dockerignore +6 -0
  33. package/templates/graphql/.env.example +3 -0
  34. package/templates/graphql/.vscode/extensions.json +3 -0
  35. package/templates/graphql/.vscode/settings.json +8 -0
  36. package/templates/graphql/Dockerfile +26 -0
  37. package/templates/graphql/README.md +185 -0
  38. package/templates/graphql/_biome.json +32 -0
  39. package/templates/graphql/codegen.ts +22 -0
  40. package/templates/graphql/gitignore +6 -0
  41. package/templates/graphql/package.json +35 -0
  42. package/templates/graphql/schema.graphql +26 -0
  43. package/templates/graphql/src/app.spec.ts +146 -0
  44. package/templates/graphql/src/app.ts +18 -0
  45. package/templates/graphql/src/context.ts +26 -0
  46. package/templates/graphql/src/env.ts +8 -0
  47. package/templates/graphql/src/generated/resolvers.ts +180 -0
  48. package/templates/graphql/src/graphql.d.ts +6 -0
  49. package/templates/graphql/src/loaders.ts +13 -0
  50. package/templates/graphql/src/resolvers.ts +39 -0
  51. package/templates/graphql/src/schema.ts +6 -0
  52. package/templates/graphql/src/server.ts +10 -0
  53. package/templates/graphql/src/store.ts +38 -0
  54. package/templates/graphql/tsconfig.json +25 -0
  55. package/templates/minimal/.dockerignore +6 -0
  56. package/templates/minimal/.vscode/extensions.json +3 -0
  57. package/templates/minimal/.vscode/settings.json +8 -0
  58. package/templates/minimal/Dockerfile +26 -0
  59. package/templates/minimal/README.md +107 -0
  60. package/templates/minimal/_biome.json +32 -0
  61. package/templates/minimal/gitignore +6 -0
  62. package/templates/minimal/package.json +25 -0
  63. package/templates/minimal/src/index.spec.ts +12 -0
  64. package/templates/minimal/src/index.ts +17 -0
  65. package/templates/minimal/tsconfig.json +25 -0
  66. package/templates/react-router/package.json +2 -2
@@ -0,0 +1,146 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { app } from "./app";
3
+ import { db, pubsub, queries } from "./store";
4
+
5
+ interface Result {
6
+ data?: Record<string, unknown>;
7
+ errors?: { message: string; extensions?: { code?: string } }[];
8
+ }
9
+
10
+ // POST /graphql in process, as a client would: no port.
11
+ async function query(
12
+ source: string,
13
+ options: { token?: string; variables?: Record<string, unknown> } = {},
14
+ ): Promise<Result> {
15
+ const response = await app.request("/graphql", {
16
+ method: "POST",
17
+ headers: {
18
+ "content-type": "application/json",
19
+ ...(options.token && { authorization: `Bearer ${options.token}` }),
20
+ },
21
+ body: JSON.stringify({ query: source, variables: options.variables }),
22
+ });
23
+ return response.json();
24
+ }
25
+
26
+ const ADD =
27
+ "mutation ($text: String!) { addNote(text: $text) { id text author { name } } }";
28
+
29
+ describe("queries", () => {
30
+ test("answers { __typename }", async () => {
31
+ expect(await query("{ __typename }")).toEqual({
32
+ data: { __typename: "Query" },
33
+ });
34
+ });
35
+
36
+ test("me is null with no token, and the user a token names", async () => {
37
+ expect((await query("{ me { name } }")).data).toEqual({ me: null });
38
+ expect((await query("{ me { name } }", { token: "wrong" })).data).toEqual({
39
+ me: null,
40
+ });
41
+ expect(
42
+ (await query("{ me { name } }", { token: "ada-token" })).data,
43
+ ).toEqual({
44
+ me: { name: "Ada" },
45
+ });
46
+ });
47
+ });
48
+
49
+ describe("mutations", () => {
50
+ test("addNote refuses a request with no token", async () => {
51
+ const { errors } = await query(ADD, { variables: { text: "Hello" } });
52
+ expect(errors?.[0]?.extensions?.code).toBe("UNAUTHENTICATED");
53
+ });
54
+
55
+ test("addNote stores the note for the viewer, and notes lists it", async () => {
56
+ const added = await query(ADD, {
57
+ token: "ada-token",
58
+ variables: { text: "Hello" },
59
+ });
60
+ expect(added.errors).toBeUndefined();
61
+ expect(added.data).toEqual({
62
+ addNote: {
63
+ id: expect.any(String),
64
+ text: "Hello",
65
+ author: { name: "Ada" },
66
+ },
67
+ });
68
+ const listed = await query("{ notes { text author { id } } }");
69
+ expect(listed.data?.["notes"]).toContainEqual({
70
+ text: "Hello",
71
+ author: { id: "1" },
72
+ });
73
+ expect(db.notes.length).toBeGreaterThan(0);
74
+ });
75
+
76
+ test("a query the schema does not have is refused", async () => {
77
+ expect((await query("{ nothing }")).errors?.[0]?.message).toContain(
78
+ "nothing",
79
+ );
80
+ });
81
+ });
82
+
83
+ describe("batching", () => {
84
+ test("the authors of N notes are loaded in one batch", async () => {
85
+ db.users.set("2", { id: "2", name: "Grace" });
86
+ db.notes.splice(0, db.notes.length);
87
+ for (let i = 1; i <= 5; i++) {
88
+ db.notes.push({
89
+ id: String(i),
90
+ text: `Note ${i}`,
91
+ authorId: String((i % 2) + 1),
92
+ });
93
+ }
94
+ queries.users = 0;
95
+ const { data, errors } = await query("{ notes { text author { name } } }");
96
+ expect(errors).toBeUndefined();
97
+ expect(data?.["notes"]).toHaveLength(5);
98
+ expect(queries.users).toBe(1);
99
+ });
100
+
101
+ test("each request gets its own loaders", async () => {
102
+ queries.users = 0;
103
+ await query("{ notes { author { name } } }");
104
+ await query("{ notes { author { name } } }");
105
+ // A cache shared between requests would answer the second without a call.
106
+ expect(queries.users).toBe(2);
107
+ });
108
+ });
109
+
110
+ describe("subscriptions", () => {
111
+ test("noteAdded streams each note over server-sent events", async () => {
112
+ const response = await app.request("/graphql", {
113
+ method: "POST",
114
+ headers: {
115
+ "content-type": "application/json",
116
+ accept: "text/event-stream",
117
+ },
118
+ body: JSON.stringify({ query: "subscription { noteAdded { text } }" }),
119
+ });
120
+ expect(response.headers.get("content-type")).toContain("text/event-stream");
121
+ const reader = response.body?.getReader();
122
+ if (reader === undefined) throw new Error("no body");
123
+ // Publish until the stream carries it: the subscription starts as it is read.
124
+ const publish = setInterval(
125
+ () =>
126
+ pubsub.publish("noteAdded", {
127
+ id: "9",
128
+ text: "Streamed",
129
+ authorId: "1",
130
+ }),
131
+ 20,
132
+ );
133
+ try {
134
+ let seen = "";
135
+ while (!seen.includes("Streamed")) {
136
+ const { done, value } = await reader.read();
137
+ if (done) throw new Error(`the stream ended: ${seen}`);
138
+ seen += new TextDecoder().decode(value);
139
+ }
140
+ expect(seen).toContain('"noteAdded":{"text":"Streamed"}');
141
+ } finally {
142
+ clearInterval(publish);
143
+ await reader.cancel();
144
+ }
145
+ });
146
+ });
@@ -0,0 +1,18 @@
1
+ import { health } from "@alxia/core";
2
+ import { graphql } from "@alxia/graphql";
3
+ import { base } from "./context";
4
+ import { createLoaders } from "./loaders";
5
+ import { schema } from "./schema";
6
+
7
+ // The probes (GET /health, GET /ready), then POST and GET /graphql, behind
8
+ // the base's middlewares. Subscriptions are served over server-sent events.
9
+ // The IDE (GraphiQL, on a browser's GET) follows alxia's dev switch: on
10
+ // under `bun dev` (NODE_ENV=development), off otherwise. `context` builds the
11
+ // loaders anew for each request, so a loader's cache is never shared.
12
+ export const app = base
13
+ .plugin(health())
14
+ .plugin((app) =>
15
+ graphql(app, { schema, context: () => ({ loaders: createLoaders() }) }),
16
+ );
17
+
18
+ export type App = typeof app;
@@ -0,0 +1,26 @@
1
+ import { alxia, defineMiddleware } from "@alxia/core";
2
+ import type { GraphQLContext } from "@alxia/graphql";
3
+ import { env } from "./env";
4
+ import type { Loaders } from "./loaders";
5
+ import { db } from "./store";
6
+
7
+ // Reads the bearer token: `viewer` is the user it names, or null. A query
8
+ // may be anonymous, so this refuses nothing; a resolver that needs a user
9
+ // refuses (`addNote`). `viewer` is typed in every resolver.
10
+ const viewerOf = defineMiddleware(({ request }, next) => {
11
+ const token = request.headers
12
+ .get("authorization")
13
+ ?.match(/^Bearer (.+)$/i)?.[1];
14
+ const id = token === undefined ? undefined : db.tokens.get(token);
15
+ return next({
16
+ viewer: (id === undefined ? undefined : db.users.get(id)) ?? null,
17
+ });
18
+ });
19
+
20
+ // The base: what every resolver reads, decorated or derived here.
21
+ export const base = alxia().decorate({ env, db }).use(viewerOf);
22
+
23
+ // A resolver's context: Yoga's, the base's (`env`, `db`, `viewer`) and the
24
+ // per-request `loaders` that src/app.ts's `context` option builds. The
25
+ // generated `Resolvers` takes it (codegen.ts: `contextType`).
26
+ export type Context = GraphQLContext<typeof base, { loaders: Loaders }>;
@@ -0,0 +1,8 @@
1
+ import { defineEnv } from "@alxia/env";
2
+ import { z } from "zod";
3
+
4
+ // Checked once, when this module is first imported: a malformed variable
5
+ // stops the process, with every issue, before it listens.
6
+ export const env = defineEnv({
7
+ PORT: z.coerce.number().default(3000),
8
+ });
@@ -0,0 +1,180 @@
1
+ import type { GraphQLResolveInfo } from 'graphql';
2
+ import type { NoteRecord } from '../store';
3
+ import type { Context } from '../context';
4
+ export type Maybe<T> = T | null;
5
+ export type InputMaybe<T> = Maybe<T>;
6
+ export type RequireFields<T, K extends keyof T> = Omit<T, K> & { [P in K]-?: NonNullable<T[P]> };
7
+ /** All built-in and custom scalars, mapped to their actual values */
8
+ export type Scalars = {
9
+ ID: { input: string; output: string; }
10
+ String: { input: string; output: string; }
11
+ Boolean: { input: boolean; output: boolean; }
12
+ Int: { input: number; output: number; }
13
+ Float: { input: number; output: number; }
14
+ };
15
+
16
+ export type Mutation = {
17
+ __typename?: 'Mutation';
18
+ /** Needs a token: `Authorization: Bearer ada-token`. */
19
+ addNote: Note;
20
+ };
21
+
22
+
23
+ export type MutationAddNoteArgs = {
24
+ text: Scalars['String']['input'];
25
+ };
26
+
27
+ export type Note = {
28
+ __typename?: 'Note';
29
+ author: User;
30
+ id: Scalars['ID']['output'];
31
+ text: Scalars['String']['output'];
32
+ };
33
+
34
+ export type Query = {
35
+ __typename?: 'Query';
36
+ /** The signed-in user, or null with no valid token. */
37
+ me?: Maybe<User>;
38
+ notes: Array<Note>;
39
+ };
40
+
41
+ export type Subscription = {
42
+ __typename?: 'Subscription';
43
+ /** Each note added, as it is added, over server-sent events. */
44
+ noteAdded: Note;
45
+ };
46
+
47
+ export type User = {
48
+ __typename?: 'User';
49
+ id: Scalars['ID']['output'];
50
+ name: Scalars['String']['output'];
51
+ };
52
+
53
+ export type WithIndex<TObject> = TObject & Record<string, any>;
54
+ export type ResolversObject<TObject> = WithIndex<TObject>;
55
+
56
+ export type ResolverTypeWrapper<T> = Promise<T> | T;
57
+
58
+
59
+ export type ResolverWithResolve<TResult, TParent, TContext, TArgs> = {
60
+ resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
61
+ };
62
+ export type Resolver<TResult, TParent = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>, TArgs = Record<PropertyKey, never>> = ResolverFn<TResult, TParent, TContext, TArgs> | ResolverWithResolve<TResult, TParent, TContext, TArgs>;
63
+
64
+ export type ResolverFn<TResult, TParent, TContext, TArgs> = (
65
+ parent: TParent,
66
+ args: TArgs,
67
+ context: TContext,
68
+ info: GraphQLResolveInfo
69
+ ) => Promise<TResult> | TResult;
70
+
71
+ export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = (
72
+ parent: TParent,
73
+ args: TArgs,
74
+ context: TContext,
75
+ info: GraphQLResolveInfo
76
+ ) => AsyncIterable<TResult> | Promise<AsyncIterable<TResult>>;
77
+
78
+ export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = (
79
+ parent: TParent,
80
+ args: TArgs,
81
+ context: TContext,
82
+ info: GraphQLResolveInfo
83
+ ) => TResult | Promise<TResult>;
84
+
85
+ export interface SubscriptionSubscriberObject<TResult, TKey extends string, TParent, TContext, TArgs> {
86
+ subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>;
87
+ resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs>;
88
+ }
89
+
90
+ export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> {
91
+ subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>;
92
+ resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>;
93
+ }
94
+
95
+ export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> =
96
+ | SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs>
97
+ | SubscriptionResolverObject<TResult, TParent, TContext, TArgs>;
98
+
99
+ export type SubscriptionResolver<TResult, TKey extends string, TParent = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>, TArgs = Record<PropertyKey, never>> =
100
+ | ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>)
101
+ | SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>;
102
+
103
+ export type TypeResolveFn<TTypes, TParent = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>> = (
104
+ parent: TParent,
105
+ context: TContext,
106
+ info: GraphQLResolveInfo
107
+ ) => Maybe<TTypes> | Promise<Maybe<TTypes>>;
108
+
109
+ export type IsTypeOfResolverFn<T = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>> = (obj: T, context: TContext, info: GraphQLResolveInfo) => boolean | Promise<boolean>;
110
+
111
+ export type NextResolverFn<T> = () => Promise<T>;
112
+
113
+ export type DirectiveResolverFn<TResult = Record<PropertyKey, never>, TParent = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>, TArgs = Record<PropertyKey, never>> = (
114
+ next: NextResolverFn<TResult>,
115
+ parent: TParent,
116
+ args: TArgs,
117
+ context: TContext,
118
+ info: GraphQLResolveInfo
119
+ ) => TResult | Promise<TResult>;
120
+
121
+
122
+
123
+
124
+
125
+ /** Mapping between all available schema types and the resolvers types */
126
+ export type ResolversTypes = ResolversObject<{
127
+ Boolean: ResolverTypeWrapper<Scalars['Boolean']['output']>;
128
+ ID: ResolverTypeWrapper<Scalars['ID']['output']>;
129
+ Mutation: ResolverTypeWrapper<Record<PropertyKey, never>>;
130
+ Note: ResolverTypeWrapper<NoteRecord>;
131
+ Query: ResolverTypeWrapper<Record<PropertyKey, never>>;
132
+ String: ResolverTypeWrapper<Scalars['String']['output']>;
133
+ Subscription: ResolverTypeWrapper<Record<PropertyKey, never>>;
134
+ User: ResolverTypeWrapper<User>;
135
+ }>;
136
+
137
+ /** Mapping between all available schema types and the resolvers parents */
138
+ export type ResolversParentTypes = ResolversObject<{
139
+ Boolean: Scalars['Boolean']['output'];
140
+ ID: Scalars['ID']['output'];
141
+ Mutation: Record<PropertyKey, never>;
142
+ Note: NoteRecord;
143
+ Query: Record<PropertyKey, never>;
144
+ String: Scalars['String']['output'];
145
+ Subscription: Record<PropertyKey, never>;
146
+ User: User;
147
+ }>;
148
+
149
+ export type MutationResolvers<ContextType = Context, ParentType extends ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation']> = ResolversObject<{
150
+ addNote?: Resolver<ResolversTypes['Note'], ParentType, ContextType, RequireFields<MutationAddNoteArgs, 'text'>>;
151
+ }>;
152
+
153
+ export type NoteResolvers<ContextType = Context, ParentType extends ResolversParentTypes['Note'] = ResolversParentTypes['Note']> = ResolversObject<{
154
+ author?: Resolver<ResolversTypes['User'], ParentType, ContextType>;
155
+ id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>;
156
+ text?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
157
+ }>;
158
+
159
+ export type QueryResolvers<ContextType = Context, ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query']> = ResolversObject<{
160
+ me?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
161
+ notes?: Resolver<Array<ResolversTypes['Note']>, ParentType, ContextType>;
162
+ }>;
163
+
164
+ export type SubscriptionResolvers<ContextType = Context, ParentType extends ResolversParentTypes['Subscription'] = ResolversParentTypes['Subscription']> = ResolversObject<{
165
+ noteAdded?: SubscriptionResolver<ResolversTypes['Note'], "noteAdded", ParentType, ContextType>;
166
+ }>;
167
+
168
+ export type UserResolvers<ContextType = Context, ParentType extends ResolversParentTypes['User'] = ResolversParentTypes['User']> = ResolversObject<{
169
+ id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>;
170
+ name?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
171
+ }>;
172
+
173
+ export type Resolvers<ContextType = Context> = ResolversObject<{
174
+ Mutation?: MutationResolvers<ContextType>;
175
+ Note?: NoteResolvers<ContextType>;
176
+ Query?: QueryResolvers<ContextType>;
177
+ Subscription?: SubscriptionResolvers<ContextType>;
178
+ User?: UserResolvers<ContextType>;
179
+ }>;
180
+
@@ -0,0 +1,6 @@
1
+ // `import typeDefs from "../schema.graphql" with { type: "text" }`: Bun
2
+ // reads the file as text, and `bun run build` puts it in dist/server.js.
3
+ declare module "*.graphql" {
4
+ const source: string;
5
+ export default source;
6
+ }
@@ -0,0 +1,13 @@
1
+ import DataLoader from "dataloader";
2
+ import { findUsers } from "./store";
3
+
4
+ // The loaders of ONE request: `context` in src/app.ts calls this per request.
5
+ // A loader batches the `load` calls made in the same tick into one call of
6
+ // its function, and caches each key it has seen, so it must never outlive the
7
+ // request: a loader shared between requests would serve one user's data to
8
+ // another, and never see a change.
9
+ export function createLoaders() {
10
+ return { user: new DataLoader(findUsers) };
11
+ }
12
+
13
+ export type Loaders = ReturnType<typeof createLoaders>;
@@ -0,0 +1,39 @@
1
+ import { GraphQLError } from "graphql";
2
+ import type { Resolvers } from "./generated/resolvers";
3
+ import { type NoteRecord, pubsub } from "./store";
4
+
5
+ // `Resolvers` is generated from schema.graphql: a field the schema lacks, or
6
+ // a return the schema's type refuses, is a compile error.
7
+ export const resolvers: Resolvers = {
8
+ Query: {
9
+ me: (_, __, { viewer }) => viewer,
10
+ notes: (_, __, { db }) => db.notes,
11
+ },
12
+ Mutation: {
13
+ addNote: (_, { text }, { viewer, db }) => {
14
+ if (viewer === null) {
15
+ throw new GraphQLError("Sign in to add a note", {
16
+ extensions: { code: "UNAUTHENTICATED" },
17
+ });
18
+ }
19
+ const note = {
20
+ id: String(db.notes.length + 1),
21
+ text,
22
+ authorId: viewer.id,
23
+ };
24
+ db.notes.push(note);
25
+ pubsub.publish("noteAdded", note);
26
+ return note;
27
+ },
28
+ },
29
+ Subscription: {
30
+ noteAdded: {
31
+ subscribe: () => pubsub.subscribe("noteAdded"),
32
+ resolve: (note: NoteRecord) => note,
33
+ },
34
+ },
35
+ Note: {
36
+ // The notes of one query load their authors in one batch (N+1 otherwise).
37
+ author: (note, _, { loaders }) => loaders.user.load(note.authorId),
38
+ },
39
+ };
@@ -0,0 +1,6 @@
1
+ import { createSchema } from "graphql-yoga";
2
+ import typeDefs from "../schema.graphql" with { type: "text" };
3
+ import type { Context } from "./context";
4
+ import { resolvers } from "./resolvers";
5
+
6
+ export const schema = createSchema<Context>({ typeDefs, resolvers });
@@ -0,0 +1,10 @@
1
+ import { app } from "./app";
2
+ import { env } from "./env";
3
+
4
+ // In dev, the URL and the route table; in production, the URL alone. On
5
+ // SIGINT and SIGTERM, listen drains the requests in flight and exits.
6
+ app.listen({
7
+ port: env.PORT,
8
+ onListen: ({ dev, table, url }) =>
9
+ console.log(dev ? table : `listening on ${url}`),
10
+ });
@@ -0,0 +1,38 @@
1
+ import { createPubSub } from "graphql-yoga";
2
+
3
+ export interface UserRecord {
4
+ id: string;
5
+ name: string;
6
+ }
7
+
8
+ export interface NoteRecord {
9
+ id: string;
10
+ text: string;
11
+ authorId: string;
12
+ }
13
+
14
+ // An in-memory store, for the example: swap it for your database.
15
+ export const db = {
16
+ users: new Map<string, UserRecord>([["1", { id: "1", name: "Ada" }]]),
17
+ // Bearer tokens and the user each one is: for development. Use a real
18
+ // session or a JWT (`@alxia/jwt`'s `bearer`) outside it.
19
+ tokens: new Map([["ada-token", "1"]]),
20
+ notes: [] as NoteRecord[],
21
+ };
22
+
23
+ // What a subscription streams: `addNote` publishes, `noteAdded` subscribes.
24
+ // One process only: across several, back it with a broker.
25
+ export const pubsub = createPubSub<{ noteAdded: [NoteRecord] }>();
26
+
27
+ // How many times the store was asked for users: a stand-in for a database's
28
+ // query log. `findUsers` is one query however many ids it is given.
29
+ export const queries = { users: 0 };
30
+
31
+ // The batch behind `loaders.user` (src/loaders.ts): one `WHERE id IN (...)` in
32
+ // a database. It answers each id in order, an Error for one that is missing.
33
+ export async function findUsers(
34
+ ids: readonly string[],
35
+ ): Promise<(UserRecord | Error)[]> {
36
+ queries.users += 1;
37
+ return ids.map((id) => db.users.get(id) ?? new Error(`No user ${id}`));
38
+ }
@@ -0,0 +1,25 @@
1
+ {
2
+ "compilerOptions": {
3
+ "types": ["bun"],
4
+ "lib": ["ESNext", "DOM"],
5
+ "target": "ESNext",
6
+ "module": "ESNext",
7
+ "moduleDetection": "force",
8
+ "moduleResolution": "bundler",
9
+ "verbatimModuleSyntax": true,
10
+ "noEmit": true,
11
+ "skipLibCheck": true,
12
+ "resolveJsonModule": true,
13
+ "strict": true,
14
+ "noImplicitOverride": true,
15
+ "noImplicitReturns": true,
16
+ "noFallthroughCasesInSwitch": true,
17
+ "noUncheckedIndexedAccess": true,
18
+ "exactOptionalPropertyTypes": true,
19
+ "noPropertyAccessFromIndexSignature": true,
20
+ "noUnusedLocals": true,
21
+ "noUnusedParameters": true,
22
+ "forceConsistentCasingInFileNames": true
23
+ },
24
+ "include": ["src"]
25
+ }
@@ -0,0 +1,6 @@
1
+ node_modules
2
+ dist
3
+ .env
4
+ .env.local
5
+ README.md
6
+ **/*.spec.ts
@@ -0,0 +1,3 @@
1
+ {
2
+ "recommendations": ["biomejs.biome"]
3
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "editor.defaultFormatter": "biomejs.biome",
3
+ "editor.formatOnSave": true,
4
+ "editor.codeActionsOnSave": {
5
+ "source.fixAll.biome": "explicit",
6
+ "source.organizeImports.biome": "explicit"
7
+ }
8
+ }
@@ -0,0 +1,26 @@
1
+ # Bun bundles the app and its dependencies into dist/index.js, and the
2
+ # image holds dist/ alone: no node_modules, no src/. Pinned to Bun 1, the
3
+ # major alxia supports.
4
+
5
+ # Every dependency, then bun run build: dist/index.js and its source map.
6
+ FROM oven/bun:1 AS build
7
+ WORKDIR /app
8
+ COPY package.json bun.lock* bunfig.toml* ./
9
+ RUN bun install --frozen-lockfile
10
+ COPY . .
11
+ RUN bun run build
12
+
13
+ # The bundle, run as Bun's own non-root user with the start script's
14
+ # command, written out so that Bun is the container's process, and
15
+ # --no-install: with no node_modules, Bun would otherwise fetch a package
16
+ # the build left out from the registry at startup, where this fails. The
17
+ # server listens on PORT (3000). On Alpine, about 200 MB lighter: the
18
+ # bundle is JavaScript, which runs the same on musl. A native addon built
19
+ # for glibc alone needs oven/bun:1 here.
20
+ FROM oven/bun:1-alpine
21
+ WORKDIR /app
22
+ ENV NODE_ENV=production
23
+ COPY --from=build /app/dist ./dist
24
+ USER bun
25
+ EXPOSE 3000
26
+ CMD ["bun", "--no-install", "dist/index.js"]