mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-14 12:14:40 +01:00
73 lines
2.1 KiB
TypeScript
73 lines
2.1 KiB
TypeScript
import { fileURLToPath } from 'url'
|
|
import { dirname, resolve } from 'path'
|
|
import { addServerHandler, addTemplate, 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 srcDir = nuxt.options.srcDir
|
|
// const root = nuxt.options.rootDir
|
|
// const clientPath = join(nuxt.options.buildDir, 'trpc-client.ts')
|
|
// const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
|
|
// const serverPath = resolve(root, 'server/fn')
|
|
const buildDir = fileURLToPath(new URL(nuxt.options.buildDir, import.meta.url))
|
|
// const rootDir = fileURLToPath(new URL(root, import.meta.url))
|
|
|
|
// nuxt.hook('config', (options) => {
|
|
// options.build.transpile.push('trpc-nuxt/client')
|
|
// })
|
|
|
|
// nuxt.hook('autoImports:extend', (imports) => {
|
|
// imports.push({
|
|
// from: clientPath,
|
|
// name: 'useServerFn',
|
|
// as: 'useServerFn',
|
|
// })
|
|
// })
|
|
|
|
const routePath = resolve(srcDir, 'server/fn/index.ts')
|
|
await fs.ensureDir(dirname(routePath))
|
|
if (!fs.existsSync(routePath)) {
|
|
await fs.writeFile(routePath, `
|
|
// 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())
|
|
}
|
|
|
|
const handlerPath = resolve(srcDir, 'server/fn')
|
|
addTemplate({
|
|
filename: 'trpc-handler.mjs',
|
|
write: true,
|
|
getContents() {
|
|
return `
|
|
import { createTRPCHandler } from 'trpc-nuxt/api'
|
|
import * as functions from "${handlerPath}"
|
|
export default createTRPCHandler({
|
|
router: functions.router
|
|
})
|
|
`.trimStart()
|
|
},
|
|
})
|
|
|
|
addServerHandler({
|
|
route: '/api/trpc/*',
|
|
handler: resolve(buildDir, 'trpc-handler.mjs'),
|
|
})
|
|
},
|
|
})
|