@alxia/create 0.1.6 → 0.2.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 (65) 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 +438 -56
  14. package/docs/roadmap.md +24 -0
  15. package/docs/troubleshooting.md +146 -50
  16. package/package.json +16 -6
  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 +6 -4
  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 +15 -5
  26. package/templates/api/src/generated/operations.ts +4 -4
  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 +171 -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 +34 -0
  42. package/templates/graphql/schema.graphql +26 -0
  43. package/templates/graphql/src/app.spec.ts +119 -0
  44. package/templates/graphql/src/app.ts +14 -0
  45. package/templates/graphql/src/context.ts +24 -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/resolvers.ts +42 -0
  50. package/templates/graphql/src/schema.ts +6 -0
  51. package/templates/graphql/src/server.ts +10 -0
  52. package/templates/graphql/src/store.ts +25 -0
  53. package/templates/graphql/tsconfig.json +25 -0
  54. package/templates/minimal/.dockerignore +6 -0
  55. package/templates/minimal/.vscode/extensions.json +3 -0
  56. package/templates/minimal/.vscode/settings.json +8 -0
  57. package/templates/minimal/Dockerfile +26 -0
  58. package/templates/minimal/README.md +107 -0
  59. package/templates/minimal/_biome.json +32 -0
  60. package/templates/minimal/gitignore +6 -0
  61. package/templates/minimal/package.json +25 -0
  62. package/templates/minimal/src/index.spec.ts +12 -0
  63. package/templates/minimal/src/index.ts +17 -0
  64. package/templates/minimal/tsconfig.json +25 -0
  65. package/templates/react-router/package.json +2 -2
@@ -0,0 +1,32 @@
1
+ {
2
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
3
+ "vcs": {
4
+ "enabled": true,
5
+ "clientKind": "git",
6
+ "useIgnoreFile": true
7
+ },
8
+ "files": {
9
+ "includes": ["**", "!!**/dist", "!!**/src/generated"]
10
+ },
11
+ "formatter": {
12
+ "enabled": true,
13
+ "indentStyle": "space"
14
+ },
15
+ "linter": {
16
+ "enabled": true,
17
+ "rules": {
18
+ "preset": "recommended",
19
+ "complexity": {
20
+ "useLiteralKeys": "off"
21
+ }
22
+ }
23
+ },
24
+ "assist": {
25
+ "enabled": true,
26
+ "actions": {
27
+ "source": {
28
+ "organizeImports": "on"
29
+ }
30
+ }
31
+ }
32
+ }
@@ -0,0 +1,22 @@
1
+ import type { CodegenConfig } from "@graphql-codegen/cli";
2
+
3
+ // `bun run generate` writes src/generated/resolvers.ts from schema.graphql:
4
+ // the schema's types and `Resolvers`, whose context is the app's own
5
+ // (`Context`, src/context.ts) and whose `Note` is the record the store holds
6
+ // (`NoteRecord`), so a resolver returns the record and `Note.author` reads it.
7
+ const config: CodegenConfig = {
8
+ schema: "schema.graphql",
9
+ generates: {
10
+ "src/generated/resolvers.ts": {
11
+ plugins: ["typescript", "typescript-resolvers"],
12
+ config: {
13
+ contextType: "../context#Context",
14
+ mappers: { Note: "../store#NoteRecord" },
15
+ useTypeImports: true,
16
+ useIndexSignature: true,
17
+ },
18
+ },
19
+ },
20
+ };
21
+
22
+ export default config;
@@ -0,0 +1,6 @@
1
+ node_modules
2
+ dist
3
+ *.log
4
+ .DS_Store
5
+ .env
6
+ .env.local
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "my-graphql-api",
3
+ "private": true,
4
+ "type": "module",
5
+ "scripts": {
6
+ "generate": "graphql-codegen --config codegen.ts",
7
+ "dev": "NODE_ENV=development bun --watch src/server.ts",
8
+ "build": "bun build src/server.ts --target=bun --outdir=dist --minify --sourcemap=linked",
9
+ "start": "NODE_ENV=production bun dist/server.js",
10
+ "test": "bun test",
11
+ "typecheck": "tsc --noEmit",
12
+ "lint": "biome lint",
13
+ "format": "biome format --write",
14
+ "check": "biome check --write",
15
+ "check:ci": "biome ci",
16
+ "verify": "bun run generate --check && bun run check:ci && bun run typecheck && bun run test"
17
+ },
18
+ "dependencies": {
19
+ "@alxia/core": "workspace:^",
20
+ "@alxia/env": "workspace:^",
21
+ "@alxia/graphql": "workspace:^",
22
+ "graphql": "^16.11.0",
23
+ "graphql-yoga": "^5.16.0",
24
+ "zod": "^4.5.4"
25
+ },
26
+ "devDependencies": {
27
+ "@biomejs/biome": "2.5.15",
28
+ "@graphql-codegen/cli": "7.4.3",
29
+ "@graphql-codegen/typescript": "6.1.0",
30
+ "@graphql-codegen/typescript-resolvers": "6.1.0",
31
+ "@types/bun": "^1.4.2",
32
+ "typescript": "^6.0.3"
33
+ }
34
+ }
@@ -0,0 +1,26 @@
1
+ type Query {
2
+ "The signed-in user, or null with no valid token."
3
+ me: User
4
+ notes: [Note!]!
5
+ }
6
+
7
+ type Mutation {
8
+ "Needs a token: `Authorization: Bearer ada-token`."
9
+ addNote(text: String!): Note!
10
+ }
11
+
12
+ type Subscription {
13
+ "Each note added, as it is added, over server-sent events."
14
+ noteAdded: Note!
15
+ }
16
+
17
+ type User {
18
+ id: ID!
19
+ name: String!
20
+ }
21
+
22
+ type Note {
23
+ id: ID!
24
+ text: String!
25
+ author: User!
26
+ }
@@ -0,0 +1,119 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { app } from "./app";
3
+ import { db, pubsub } 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("subscriptions", () => {
84
+ test("noteAdded streams each note over server-sent events", async () => {
85
+ const response = await app.request("/graphql", {
86
+ method: "POST",
87
+ headers: {
88
+ "content-type": "application/json",
89
+ accept: "text/event-stream",
90
+ },
91
+ body: JSON.stringify({ query: "subscription { noteAdded { text } }" }),
92
+ });
93
+ expect(response.headers.get("content-type")).toContain("text/event-stream");
94
+ const reader = response.body?.getReader();
95
+ if (reader === undefined) throw new Error("no body");
96
+ // Publish until the stream carries it: the subscription starts as it is read.
97
+ const publish = setInterval(
98
+ () =>
99
+ pubsub.publish("noteAdded", {
100
+ id: "9",
101
+ text: "Streamed",
102
+ authorId: "1",
103
+ }),
104
+ 20,
105
+ );
106
+ try {
107
+ let seen = "";
108
+ while (!seen.includes("Streamed")) {
109
+ const { done, value } = await reader.read();
110
+ if (done) throw new Error(`the stream ended: ${seen}`);
111
+ seen += new TextDecoder().decode(value);
112
+ }
113
+ expect(seen).toContain('"noteAdded":{"text":"Streamed"}');
114
+ } finally {
115
+ clearInterval(publish);
116
+ await reader.cancel();
117
+ }
118
+ });
119
+ });
@@ -0,0 +1,14 @@
1
+ import { health } from "@alxia/core";
2
+ import { graphql } from "@alxia/graphql";
3
+ import { base } from "./context";
4
+ import { schema } from "./schema";
5
+
6
+ // The probes (GET /health, GET /ready), then POST and GET /graphql, behind
7
+ // the base's middlewares. Subscriptions are served over server-sent events.
8
+ // The IDE (GraphiQL, on a browser's GET) follows alxia's dev switch: on
9
+ // under `bun dev` (NODE_ENV=development), off otherwise.
10
+ export const app = base
11
+ .plugin(health())
12
+ .plugin((app) => graphql(app, { schema }));
13
+
14
+ export type App = typeof app;
@@ -0,0 +1,24 @@
1
+ import { alxia, defineMiddleware } from "@alxia/core";
2
+ import type { GraphQLContext } from "@alxia/graphql";
3
+ import { env } from "./env";
4
+ import { db } from "./store";
5
+
6
+ // Reads the bearer token: `viewer` is the user it names, or null. A query
7
+ // may be anonymous, so this refuses nothing; a resolver that needs a user
8
+ // refuses (`addNote`). `viewer` is typed in every resolver.
9
+ const viewerOf = defineMiddleware(({ request }, next) => {
10
+ const token = request.headers
11
+ .get("authorization")
12
+ ?.match(/^Bearer (.+)$/i)?.[1];
13
+ const id = token === undefined ? undefined : db.tokens.get(token);
14
+ return next({
15
+ viewer: (id === undefined ? undefined : db.users.get(id)) ?? null,
16
+ });
17
+ });
18
+
19
+ // The base: what every resolver reads, decorated or derived here.
20
+ export const base = alxia().decorate({ env, db }).use(viewerOf);
21
+
22
+ // A resolver's context: Yoga's, and the base's (`env`, `db`, `viewer`).
23
+ // The generated `Resolvers` takes it (codegen.ts: `contextType`).
24
+ export type Context = GraphQLContext<typeof base>;
@@ -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,42 @@
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
+ author: (note, _, { db }) => {
37
+ const author = db.users.get(note.authorId);
38
+ if (author === undefined) throw new Error(`No user ${note.authorId}`);
39
+ return author;
40
+ },
41
+ },
42
+ };
@@ -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,25 @@
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] }>();
@@ -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"]