Skip to content
Open
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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,15 @@
"@trpc/client": "^10.16.0",
"@trpc/server": "^10.16.0",
"astro": "^2.0.18",
"cloudflare-pages-plugin-trpc": "^0.3.2",
"uuid": "^9.0.0",
"zod": "^3.21.4"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20230307.0",
"@databases/split-sql-query": "^1.0.3",
"@databases/sql": "^3.3.0",
"@types/uuid": "^9.0.1",
"wrangler": "^2.12.3"
}
}
38 changes: 38 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 15 additions & 11 deletions src/pages/api/trpc/[trpc].ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { initTRPC } from '@trpc/server';
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import { Context, createContext } from './context';
import { Context, createContext, Env } from './context';
import { z } from 'zod';
import type { APIRoute } from 'astro';
import tRPCPlugin from "cloudflare-pages-plugin-trpc";

type User = {
id: string;
name: string;
Expand All @@ -19,30 +19,34 @@ const appRouter = t.router({
getUserById: t.procedure.input(z.string()).query(({ input }) => {
return users[input]; // input type is string
}),
getUsers: t.procedure.query(({ctx}) => {
const result = ctx.db.exec('SELECT * FROM users');
console.log({result});
return result;
}),
createUser: t.procedure
// validate input with Zod
.input(
z.object({
name: z.string().min(3),
bio: z.string().max(142).optional(),
}),
)
.mutation(({ input }) => {
.mutation(({ input, ctx }) => {
const id = Date.now().toString();
const statement = ctx.db.prepare("INSERT INTO users (id, title, body) VALUES (?, ?, ?)").bind(id, input.name, input.bio);
const result = statement.run();
console.log({result})

const user: User = { id, ...input };
users[user.id] = user;
return id;
})
});

// The Astro API route, handling all incoming HTTP requests.
export const all: APIRoute = ({ request }) => {
return fetchRequestHandler({
req: request,
export const all: PagesFunction<Env> = tRPCPlugin({
endpoint: '/api/trpc',
router: appRouter,
createContext
createContext,
});
};

export type AppRouter = typeof appRouter;
22 changes: 16 additions & 6 deletions src/pages/api/trpc/context.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
import type { inferAsyncReturnType } from '@trpc/server';
import type { FetchCreateContextFnOptions } from '@trpc/server/adapters/fetch';
import type { FetchCreateContextWithCloudflareEnvFnOptions } from 'cloudflare-pages-plugin-trpc';

export function createContext({
// Define binding to allow your worker to interact with Cloudflare D1.
export interface Env {
DB: D1Database;
}

export async function createContext({
req,
resHeaders,
}: FetchCreateContextFnOptions) {
env
}: FetchCreateContextWithCloudflareEnvFnOptions<Env>) {
const user = { name: req.headers.get('username') ?? 'anonymous' };
return { req, resHeaders, user };
}

return {
db: env.DB,
req,
user
};
};
export type Context = inferAsyncReturnType<typeof createContext>;
3 changes: 2 additions & 1 deletion src/pages/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ const userId = await client.createUser.mutate({
bio: "gardener",
});
const user = await client.getUserById.query(userId);

const users = await client.getUsers.query();
console.log({users});
// Logged server-side (in cloudflare)
console.log({ user });
---
Expand Down
5 changes: 4 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
{
"extends": "astro/tsconfigs/strict"
"extends": "astro/tsconfigs/strict",
"compilerOptions": {
"types": ["@cloudflare/workers-types"]
}
}