update types

This commit is contained in:
Robert Soriano
2022-05-17 14:25:03 -07:00
parent bb5dc377d5
commit 9fac4ac4d9
25 changed files with 479 additions and 363 deletions

View File

@@ -1,7 +0,0 @@
node_modules
*.log*
.nuxt
.nitro
.cache
.output
.env

View File

@@ -1,42 +0,0 @@
# Nuxt 3 Minimal Starter
Look at the [nuxt 3 documentation](https://v3.nuxtjs.org) to learn more.
## Setup
Make sure to install the dependencies:
```bash
# yarn
yarn install
# npm
npm install
# pnpm
pnpm install --shamefully-hoist
```
## Development Server
Start the development server on http://localhost:3000
```bash
npm run dev
```
## Production
Build the application for production:
```bash
npm run build
```
Locally preview production build:
```bash
npm run preview
```
Checkout the [deployment documentation](https://v3.nuxtjs.org/docs/deployment) for more information.

View File

@@ -1,18 +0,0 @@
<script setup lang="ts">
const { data, error } = useTrpcQuery('hello')
// const d = useLazyAsyncData('asd', () => $fetch('/api/hello'))
watch(data, (val) => {
console.log('val', val)
console.log('error', error.value)
}, {
immediate: true,
})
</script>
<template>
<div>
{{ data }}
</div>
</template>

View File

@@ -1,6 +0,0 @@
import { defineNuxtConfig } from 'nuxt'
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
modules: ['trpc-nuxt'],
})

View File

@@ -1,18 +0,0 @@
{
"name": "playground",
"private": true,
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview",
"prepare": "nuxt prepare"
},
"dependencies": {
"trpc-nuxt": "link:../trpc",
"zod": "^3.16.0"
},
"devDependencies": {
"nuxt": "3.0.0-rc.3"
}
}

View File

@@ -1,11 +0,0 @@
// generated by trpc-nuxt
import * as trpc from '@trpc/server'
export const router = trpc
.router()
.query('hello', {
resolve: () => 'world',
});
export type Router = typeof router

View File

@@ -1,3 +0,0 @@
{
"extends": "./.nuxt/tsconfig.json"
}

View File

@@ -1,6 +0,0 @@
# Nuxt Module
## Development
- Run `npm run dev:prepare` to generate type stubs.
- Use `npm run dev` to start [playground](./playground) in development mode.

View File

@@ -1 +0,0 @@
export * from './dist/runtime/client'

View File

@@ -1 +0,0 @@
export * from './dist/runtime/handler'

View File

@@ -1,45 +0,0 @@
{
"name": "trpc-nuxt",
"type": "module",
"version": "0.0.3",
"license": "MIT",
"main": "./dist/module.cjs",
"types": "./dist/types.d.ts",
"exports": {
".": {
"import": "./dist/module.mjs",
"require": "./dist/module.cjs"
},
"./api": {
"import": "./dist/runtime/api.mjs",
"types": "./dist/runtime/api.d.ts"
},
"./client": {
"import": "./dist/runtime/client.mjs",
"types": "./dist/runtime/client.d.ts"
}
},
"files": [
"dist",
"*.d.ts"
],
"scripts": {
"build": "nuxt-module-build",
"dev": "nuxt-module-build --stub"
},
"dependencies": {
"@nuxt/kit": "^3.0.0-rc.3",
"@trpc/client": "^9.23.3",
"@trpc/server": "^9.23.2",
"fs-extra": "^10.1.0",
"h3": "^0.7.8",
"ohash": "^0.1.0",
"pathe": "^0.3.0",
"ufo": "^0.8.4"
},
"devDependencies": {
"@nuxt/module-builder": "latest",
"@types/fs-extra": "^9.0.13",
"nuxt": "^3.0.0-rc.3"
}
}

View File

@@ -1,93 +0,0 @@
import { dirname, join, resolve } from 'pathe'
import { addServerHandler, defineNuxtModule } from '@nuxt/kit'
import fs from 'fs-extra'
export interface ModuleOptions {}
export default defineNuxtModule<ModuleOptions>({
meta: {
name: 'trpc-nuxt',
configKey: 'trpc',
},
defaults: {},
async setup(_options, nuxt) {
const clientPath = join(nuxt.options.buildDir, 'trpc-client.ts')
const handlerPath = join(nuxt.options.buildDir, 'trpc-handler.ts')
nuxt.hook('config', () => {
nuxt.options.build.transpile.push('trpc-nuxt/client')
})
addServerHandler({
route: '/trpc/*',
handler: handlerPath,
})
nuxt.hook('autoImports:extend', (imports) => {
imports.push(
{ name: 'useTrpcQuery', from: clientPath },
{ name: 'useTrpcLazyQuery', from: clientPath },
{ name: 'useTrpcMutation', from: clientPath },
)
})
const srcDir = nuxt.options.srcDir
const optionsPath = resolve(srcDir, 'server/fn/index.ts')
await fs.ensureDir(dirname(clientPath))
nuxt.options.build.transpile.push('trpc-nuxt/client')
nuxt.hook('autoImports:extend', (imports) => {
imports.push(
{ name: 'useTrpcQuery', as: 'useTrpcQuery', from: clientPath },
{ name: 'useTrpcLazyQuery', as: 'useTrpcLazyQuery', from: clientPath },
{ name: 'useTrpcMutation', as: 'useTrpcMutation', from: clientPath },
)
})
await fs.writeFile(clientPath, `
import * as trpc from '@trpc/client'
import { createTRPCComposables } from 'trpc-nuxt/client'
import { router } from '~/server/fn'
const client = trpc.createTRPCClient<typeof router>({
url: process.browser ? '/trpc' : 'http://localhost:3000/trpc',
})
const {
useTrpcQuery,
useTrpcLazyQuery,
useTrpcMutation
} = createTRPCComposables(client)
export {
useTrpcQuery,
useTrpcLazyQuery,
useTrpcMutation
}
`)
await fs.writeFile(handlerPath, `
import { createTRPCHandler } from 'trpc-nuxt/api'
import * as functions from '~/server/fn'
export default createTRPCHandler({
router: functions.router
})
`)
if (!fs.existsSync(optionsPath)) {
await fs.writeFile(optionsPath, `
// Generated by trpc-nuxt
import * as trpc from '@trpc/server'
export const router = trpc
.router()
.query('hello', {
resolve: () => 'world',
});
export type Router = typeof router
`.trimStart())
}
},
})

View File

@@ -1,69 +0,0 @@
import { resolveHTTPResponse } from '@trpc/server'
import type {
AnyRouter,
ProcedureType,
ResponseMeta,
TRPCError,
inferRouterContext,
inferRouterError,
} from '@trpc/server'
import { createURL } from 'ufo'
import type { IncomingMessage } from 'h3'
import type { TRPCResponse } from '@trpc/server/dist/declarations/src/rpc'
import { isMethod, useBody } from 'h3'
type MaybePromise<T> = T | Promise<T>
type CreateContextFn<TRouter extends AnyRouter> = (req: IncomingMessage) => MaybePromise<inferRouterContext<TRouter>>
type ResponseMetaFn<TRouter extends AnyRouter> = (opts: {
data: TRPCResponse<unknown, inferRouterError<TRouter>>[]
ctx?: inferRouterContext<TRouter>
paths?: string[]
type: ProcedureType | 'unknown'
errors: TRPCError[]
}) => ResponseMeta
export function createTRPCHandler<Router extends AnyRouter>({
router,
createContext,
responseMeta,
}: {
router: Router
createContext?: CreateContextFn<Router>
responseMeta?: ResponseMetaFn<Router>
}) {
const url = '/trpc'
return async (event) => {
const {
req,
res,
} = event
const $url = createURL(req.url)
const httpResponse = await resolveHTTPResponse({
router,
req: {
method: req.method,
headers: req.headers,
body: isMethod(event, 'GET') ? null : await useBody(event),
query: $url.searchParams,
},
path: $url.pathname.substring(url.length + 1),
createContext: async () => createContext?.(req),
responseMeta,
})
const { status, headers, body } = httpResponse
res.statusCode = status
Object.keys(headers).forEach((key) => {
res.setHeader(key, headers[key])
})
return body
}
}

View File

@@ -1,33 +0,0 @@
import { objectHash } from 'ohash'
import type { TRPCClient } from '@trpc/client'
import { useAsyncData, useLazyAsyncData } from '#imports'
// type ReturnType<T> = T extends (...args: any) => infer R ? R : never
export function createTRPCComposables<T extends TRPCClient<any>>(client: T): {
useTrpcQuery: (...args: Parameters<typeof client['query']>) => ReturnType<typeof useAsyncData>
useTrpcLazyQuery: (...args: Parameters<typeof client['query']>) => ReturnType<typeof useLazyAsyncData>
useTrpcMutation: (...args: Parameters<typeof client['mutation']>) => ReturnType<typeof useAsyncData>
}
export function createTRPCComposables<
T extends TRPCClient<any>,
>(client: T) {
const useTrpcQuery = (...args: Parameters<typeof client.query>) => {
return useAsyncData(`trpc-${objectHash(args[0] + (args[1] ? JSON.stringify(args[1]) : ''))}`, () => client.query(...args))
}
const useTrpcLazyQuery = (...args: Parameters<typeof client.query>) => {
return useLazyAsyncData(`trpc-${objectHash(args[0] + (args[1] ? JSON.stringify(args[1]) : ''))}`, () => client.query(...args))
}
const useTrpcMutation = (...args: Parameters<typeof client.mutation>) => {
return useAsyncData(`trpc-${objectHash(args[0] + (args[1] ? JSON.stringify(args[1]) : ''))}`, () => client.mutation(...args))
}
return {
useTrpcQuery,
useTrpcLazyQuery,
useTrpcMutation,
}
}

View File

@@ -1,14 +0,0 @@
{
"compilerOptions": {
"target": "es2018",
"module": "esnext",
"lib": ["esnext"],
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true,
"strictNullChecks": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"skipDefaultLibCheck": true
}
}