Skip to content

Commit

Permalink
add working example
Browse files Browse the repository at this point in the history
  • Loading branch information
cah4a committed Jul 1, 2024
1 parent dee82a5 commit 6773326
Show file tree
Hide file tree
Showing 9 changed files with 369 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ Check that it works:
curl http://localhost:3000/ping
```

## Example

for a full example, see the [example](./example/) directory.

## API Reference

Ensure you have created a `router.ts` file as outlined in the tRPC documentation: [Define Routers](https://trpc.io/docs/server/routers).
Expand Down
175 changes: 175 additions & 0 deletions example/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore

# Logs

logs
_.log
npm-debug.log_
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Caches

.cache

# Diagnostic reports (https://nodejs.org/api/report.html)

report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json

# Runtime data

pids
_.pid
_.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover

lib-cov

# Coverage directory used by tools like istanbul

coverage
*.lcov

# nyc test coverage

.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)

.grunt

# Bower dependency directory (https://bower.io/)

bower_components

# node-waf configuration

.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)

build/Release

# Dependency directories

node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)

web_modules/

# TypeScript cache

*.tsbuildinfo

# Optional npm cache directory

.npm

# Optional eslint cache

.eslintcache

# Optional stylelint cache

.stylelintcache

# Microbundle cache

.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history

.node_repl_history

# Output of 'npm pack'

*.tgz

# Yarn Integrity file

.yarn-integrity

# dotenv environment variable files

.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)

.parcel-cache

# Next.js build output

.next
out

# Nuxt.js build / generate output

.nuxt
dist

# Gatsby files

# Comment in the public line in if your project uses Gatsby and not Next.js

# https://nextjs.org/blog/next-9-1#public-directory-support

# public

# vuepress build output

.vuepress/dist

# vuepress v2.x temp and cache directory

.temp

# Docusaurus cache and generated files

.docusaurus

# Serverless directories

.serverless/

# FuseBox cache

.fusebox/

# DynamoDB Local files

.dynamodb/

# TernJS port file

.tern-port

# Stores VSCode versions used for testing VSCode extensions

.vscode-test

# yarn v2

.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

# IntelliJ based IDEs
.idea

# Finder (MacOS) folder config
.DS_Store
15 changes: 15 additions & 0 deletions example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# trpc-bun-adapter-example

To install dependencies:

```bash
bun install
```

To run:

```bash
bun run index.ts
```

This project was created using `bun init` in bun v1.1.10. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
Binary file added example/bun.lockb
Binary file not shown.
64 changes: 64 additions & 0 deletions example/client/app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import React, { useState } from "react";
import ReactDOM from "react-dom/client";

import type { AppRouter } from "../server";
import {
createTRPCReact,
createWSClient,
httpLink,
splitLink,
wsLink,
} from "@trpc/react-query";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

const trpc = createTRPCReact<AppRouter>();

function App() {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({
links: [
splitLink({
condition: (op) => op.type === "subscription",
true: wsLink({
client: createWSClient({
url: "ws://localhost:3000/trpc",
}),
}),
false: httpLink({ url: "http://localhost:3000/trpc" }),
}),
],
}),
);
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
<div style={{ padding: 20 }}>
<QueryExample />
<SubscribeExample />
</div>
</QueryClientProvider>
</trpc.Provider>
);
}

function QueryExample() {
const { data } = trpc.ping.useQuery();
return <div>Ping query: {data}</div>;
}

function SubscribeExample() {
const [number, setNumber] = useState<number>();

trpc.subscribe.useSubscription(undefined, {
onData(data) {
setNumber(data);
},
});

return <div>Subscribe: {number}</div>;
}

const root = ReactDOM.createRoot(document.getElementById("root")!);

root.render(<App />);
14 changes: 14 additions & 0 deletions example/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>TRPC BUN AND FUN</title>
</head>
<body>
<div id="root"></div>
<script src="/app.js" lang="javascript"></script>
</body>
</html>
27 changes: 27 additions & 0 deletions example/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "trpc-bun-adapter-example",
"module": "server.ts",
"type": "module",
"scripts": {
"start": "bun server/index.ts --watch",
"bundle": "bun build --outdir dist client/app.tsx"
},
"devDependencies": {
"@types/bun": "latest",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0"
},
"peerDependencies": {
"typescript": "^5.0.0"
},
"dependencies": {
"@tanstack/react-query": "^5.49.2",
"@trpc/client": "^11.0.0-rc.433",
"@trpc/next": "^11.0.0-rc.433",
"@trpc/react-query": "^11.0.0-rc.433",
"@trpc/server": "^11.0.0-rc.433",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"trpc-bun-adapter": "^1.1.0"
}
}
43 changes: 43 additions & 0 deletions example/server/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { initTRPC } from "@trpc/server";
import { createBunServeHandler } from "trpc-bun-adapter";
import { observable } from "@trpc/server/observable";

const t = initTRPC.create();

export const router = t.router({
ping: t.procedure.query(() => {
return "pong";
}),

subscribe: t.procedure.subscription(() => {
return observable<number>((emit) => {
emit.next(Math.random());
emit.complete();
});
}),
});

export type AppRouter = typeof router;

Bun.serve(
createBunServeHandler(
{
endpoint: "/trpc",
router,
},
{
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/app.js") {
return new Response(Bun.file("./dist/app.js"));
}

if (url.pathname === "/") {
return new Response(Bun.file("./index.html"));
}

return new Response("Not found", { status: 404 });
},
},
),
);
27 changes: 27 additions & 0 deletions example/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"compilerOptions": {
// Enable latest features
"lib": ["ESNext", "DOM"],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",
"jsx": "react-jsx",
"allowJs": true,

// Bundler mode
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,

// Best practices
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,

// Some stricter flags (disabled by default)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false
}
}

0 comments on commit 6773326

Please sign in to comment.