- Built with ❤️ by{' '}
+ Built with ❤️ by
+ {' '}
{
- // biome-ignore lint/suspicious/noConsole:
+ // eslint-disable-next-line no-console
console.log('Server is available at http://localhost:2026')
})
```
diff --git a/apps/content/examples/contract.ts b/apps/content/examples/contract.ts
index 9df1bedd..b6e58f80 100644
--- a/apps/content/examples/contract.ts
+++ b/apps/content/examples/contract.ts
@@ -2,6 +2,19 @@ import { oc } from '@orpc/contract'
import { oz } from '@orpc/zod'
import { z } from 'zod'
+// Implement the contract
+
+import { ORPCError, os } from '@orpc/server'
+
+// Expose apis to the internet with fetch handler
+
+import { createFetchHandler } from '@orpc/server/fetch'
+
+// Modern runtime that support fetch api like deno, bun, cloudflare workers, even node can used
+
+import { createServer } from 'node:http'
+import { createServerAdapter } from '@whatwg-node/server'
+
// Define your contract first
// This contract can replace server router in most-case
@@ -55,10 +68,6 @@ export const contract = oc.router({
}),
})
-// Implement the contract
-
-import { os, ORPCError } from '@orpc/server'
-
export type Context = { user?: { id: string } }
export const base = os.context()
export const pub /** os with ... */ = base.contract(contract) // Ensure every implement must be match contract
@@ -112,20 +121,11 @@ export const router = pub.router({
},
})
-// Expose apis to the internet with fetch handler
-
-import { createFetchHandler } from '@orpc/server/fetch'
-
const handler = createFetchHandler({
router,
serverless: false, // set true will improve cold start times
})
-// Modern runtime that support fetch api like deno, bun, cloudflare workers, even node can used
-
-import { createServer } from 'node:http'
-import { createServerAdapter } from '@whatwg-node/server'
-
const server = createServer(
createServerAdapter((request: Request) => {
const url = new URL(request.url)
@@ -143,7 +143,7 @@ const server = createServer(
)
server.listen(2026, () => {
- // biome-ignore lint/suspicious/noConsole:
+ // eslint-disable-next-line no-console
console.log('Server is available at http://localhost:2026')
})
diff --git a/apps/content/examples/middleware.ts b/apps/content/examples/middleware.ts
index 00b1cb03..648df954 100644
--- a/apps/content/examples/middleware.ts
+++ b/apps/content/examples/middleware.ts
@@ -1,4 +1,4 @@
-import { os, ORPCError } from '@orpc/server'
+import { ORPCError, os } from '@orpc/server'
import { z } from 'zod'
// in oRPC middleware is so powerful
@@ -12,7 +12,7 @@ export const pub /** public access */ = os
const start = Date.now()
meta.onFinish((output, error) => {
- // biome-ignore lint/suspicious/noConsole:
+ // eslint-disable-next-line no-console
console.log(`middleware cost ${Date.now() - start}ms`)
})
})
@@ -23,11 +23,11 @@ export const authMid = pub.middleware(async (input, context, meta) => {
}
meta.onSuccess((output) => {})
- meta.onSuccess((error) => {})
+ meta.onSuccess((_error) => {})
meta.onFinish((output, error) => {})
- meta.path // for analyze
- meta.procedure // for analyze
+ const _path = meta.path // for analyze
+ const _procedure = meta.procedure // for analyze
return {
context: {
@@ -51,7 +51,7 @@ export const editPost = authed
.input(z.object({ id: z.string() }))
.output(z.string())
.use(canEditPost) // if input not match, will throw type error
- .use(canEditPost, (old) => ({ id: old.id })) // Can map input if needed
+ .use(canEditPost, old => ({ id: old.id })) // Can map input if needed
.use((input, context, meta) => {
// If middleware create after .input and .output them will be typed
diff --git a/apps/content/examples/open-api.ts b/apps/content/examples/open-api.ts
index 4a7d931d..2366a23d 100644
--- a/apps/content/examples/open-api.ts
+++ b/apps/content/examples/open-api.ts
@@ -1,6 +1,9 @@
import { generateOpenAPI } from '@orpc/openapi'
import { router } from 'examples/server'
+// or generate from contract
+import { contract } from 'examples/contract'
+
export const specFromServerRouter = generateOpenAPI({
router,
info: {
@@ -9,9 +12,6 @@ export const specFromServerRouter = generateOpenAPI({
},
})
-// or generate from contract
-import { contract } from 'examples/contract'
-
export const specFromContractRouter = generateOpenAPI({
router: contract,
info: {
@@ -47,7 +47,7 @@ const _exampleSpec = {
},
},
responses: {
- '200': {
+ 200: {
description: 'OK',
content: {
'application/json': {
@@ -80,7 +80,7 @@ const _exampleSpec = {
},
],
responses: {
- '200': {
+ 200: {
description: 'OK',
content: {
'application/json': {
@@ -132,7 +132,7 @@ const _exampleSpec = {
},
},
responses: {
- '200': {
+ 200: {
description: 'OK',
content: {
'application/json': {
diff --git a/apps/content/examples/react.ts b/apps/content/examples/react.ts
index 1bcdc153..bde0496b 100644
--- a/apps/content/examples/react.ts
+++ b/apps/content/examples/react.ts
@@ -1,7 +1,6 @@
-import { createORPCReact } from '@orpc/react'
import type { router } from 'examples/server'
+import { createORPCReact } from '@orpc/react'
// biome-ignore lint/correctness/noUnusedImports:
-import * as React from 'react'
-export const { orpc, ORPCContext } =
- createORPCReact()
+export const { orpc, ORPCContext }
+ = createORPCReact()
diff --git a/apps/content/examples/server-action.tsx b/apps/content/examples/server-action.tsx
index 6e059508..f19dae45 100644
--- a/apps/content/examples/server-action.tsx
+++ b/apps/content/examples/server-action.tsx
@@ -1,11 +1,11 @@
'use server'
-// biome-ignore lint/correctness/noUnusedImports:
-import * as React from 'react'
-
import { os } from '@orpc/server'
+
import { oz } from '@orpc/zod'
import { redirect } from 'next/navigation'
+// biome-ignore lint/correctness/noUnusedImports:
+import * as React from 'react'
import { z } from 'zod'
export const createPost = os
diff --git a/apps/content/examples/server.ts b/apps/content/examples/server.ts
index b2b6126d..2034e082 100644
--- a/apps/content/examples/server.ts
+++ b/apps/content/examples/server.ts
@@ -1,7 +1,16 @@
-import { os, ORPCError } from '@orpc/server'
+import { ORPCError, os } from '@orpc/server'
import { oz } from '@orpc/zod'
import { z } from 'zod'
+// Expose apis to the internet with fetch handler
+
+import { createFetchHandler } from '@orpc/server/fetch'
+
+// Modern runtime that support fetch api like deno, bun, cloudflare workers, even node can used
+
+import { createServer } from 'node:http'
+import { createServerAdapter } from '@whatwg-node/server'
+
export type Context = { user?: { id: string } }
// global pub, authed completely optional
@@ -75,7 +84,7 @@ export const router = pub.router({
}),
)
.handler(async (input, context, meta) => {
- input.thumb // file upload out of the box
+ const _thumb = input.thumb // file upload out of the box
return {
id: 'example',
@@ -86,20 +95,11 @@ export const router = pub.router({
}),
})
-// Expose apis to the internet with fetch handler
-
-import { createFetchHandler } from '@orpc/server/fetch'
-
const handler = createFetchHandler({
router,
serverless: false, // set true will improve cold start times
})
-// Modern runtime that support fetch api like deno, bun, cloudflare workers, even node can used
-
-import { createServer } from 'node:http'
-import { createServerAdapter } from '@whatwg-node/server'
-
const server = createServer(
createServerAdapter((request: Request) => {
const url = new URL(request.url)
@@ -117,7 +117,7 @@ const server = createServer(
)
server.listen(2026, () => {
- // biome-ignore lint/suspicious/noConsole:
+ // eslint-disable-next-line no-console
console.log('Server is available at http://localhost:2026')
})
diff --git a/apps/content/lib/source.ts b/apps/content/lib/source.ts
index 2e601648..7905732b 100644
--- a/apps/content/lib/source.ts
+++ b/apps/content/lib/source.ts
@@ -9,10 +9,11 @@ export const source = loader({
baseUrl: '/docs',
source: createMDXSource(docs, meta),
icon(icon) {
- if (icon && icon in icons)
+ if (icon && icon in icons) {
return createElement(IconContainer, {
icon: icons[icon as keyof typeof icons],
})
+ }
},
})
diff --git a/apps/content/tsconfig.json b/apps/content/tsconfig.json
index 1bb76006..0b35c5c4 100644
--- a/apps/content/tsconfig.json
+++ b/apps/content/tsconfig.json
@@ -1,23 +1,23 @@
{
"compilerOptions": {
- "baseUrl": ".",
+ "incremental": true,
"target": "ESNext",
+ "jsx": "preserve",
"lib": ["dom", "dom.iterable", "esnext"],
- "allowJs": true,
- "skipLibCheck": true,
- "strict": true,
- "forceConsistentCasingInFileNames": true,
- "noEmit": true,
- "esModuleInterop": true,
+ "baseUrl": ".",
"module": "esnext",
"moduleResolution": "bundler",
- "resolveJsonModule": true,
- "isolatedModules": true,
- "jsx": "preserve",
- "incremental": true,
"paths": {
"@/*": ["./*"]
},
+ "resolveJsonModule": true,
+ "allowJs": true,
+ "strict": true,
+ "noEmit": true,
+ "esModuleInterop": true,
+ "forceConsistentCasingInFileNames": true,
+ "isolatedModules": true,
+ "skipLibCheck": true,
"plugins": [
{
"name": "next"
diff --git a/eslint.config.js b/eslint.config.js
index e6b09160..fcde1927 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -1,7 +1,6 @@
import antfu from '@antfu/eslint-config'
export default antfu({
- type: 'lib',
react: true,
formatters: true,
}, {
@@ -16,11 +15,6 @@ export default antfu({
'unused-imports/no-unused-vars': 'off',
'antfu/no-top-level-await': 'off',
},
-}, {
- files: ['apps/**', 'playgrounds/**'],
- rules: {
- 'ts/explicit-function-return-type': 'off',
- },
}, {
files: ['playgrounds/**'],
rules: {
diff --git a/packages/client/package.json b/packages/client/package.json
index f0135562..8714960d 100644
--- a/packages/client/package.json
+++ b/packages/client/package.json
@@ -40,15 +40,15 @@
"build:watch": "pnpm run build --watch",
"type:check": "tsc -b"
},
- "devDependencies": {
- "zod": "^3.23.8"
+ "peerDependencies": {
+ "@orpc/contract": "workspace:*",
+ "@orpc/server": "workspace:*"
},
"dependencies": {
"@orpc/shared": "workspace:*",
"@orpc/transformer": "workspace:*"
},
- "peerDependencies": {
- "@orpc/contract": "workspace:*",
- "@orpc/server": "workspace:*"
+ "devDependencies": {
+ "zod": "^3.23.8"
}
}
diff --git a/packages/client/src/procedure.test.ts b/packages/client/src/procedure.test.ts
index 6a9593d0..58dd57b9 100644
--- a/packages/client/src/procedure.test.ts
+++ b/packages/client/src/procedure.test.ts
@@ -1,4 +1,4 @@
-import { os, ORPCError } from '@orpc/server'
+import { ORPCError, os } from '@orpc/server'
import { createFetchHandler } from '@orpc/server/fetch'
import { z } from 'zod'
import { createProcedureClient } from './procedure'
@@ -111,7 +111,7 @@ describe('createProcedureClient', () => {
const router = os.router({
ping: os
.input(z.object({ value: z.date() }))
- .handler((input) => input.value),
+ .handler(input => input.value),
})
const handler = createFetchHandler({
@@ -167,7 +167,8 @@ describe('createProcedureClient', () => {
let error: any
try {
await client(undefined)
- } catch (e) {
+ }
+ catch (e) {
error = e
}
diff --git a/packages/client/src/procedure.ts b/packages/client/src/procedure.ts
index 210cb607..15ff6e83 100644
--- a/packages/client/src/procedure.ts
+++ b/packages/client/src/procedure.ts
@@ -1,6 +1,7 @@
///
///
+import type { Promisable } from '@orpc/shared'
import {
ORPC_HEADER,
ORPC_HEADER_VALUE,
@@ -8,7 +9,6 @@ import {
type SchemaInput,
type SchemaOutput,
} from '@orpc/contract'
-import type { Promisable } from '@orpc/shared'
import { trim } from '@orpc/shared'
import { ORPCError } from '@orpc/shared/error'
import { ORPCDeserializer, ORPCSerializer } from '@orpc/transformer'
@@ -80,7 +80,8 @@ export function createProcedureClient<
const json = await (async () => {
try {
return await deserializer.deserialize(response)
- } catch (e) {
+ }
+ catch (e) {
throw new ORPCError({
code: 'INTERNAL_SERVER_ERROR',
message: 'Cannot parse response.',
@@ -91,8 +92,8 @@ export function createProcedureClient<
if (!response.ok) {
throw (
- ORPCError.fromJSON(json) ??
- new ORPCError({
+ ORPCError.fromJSON(json)
+ ?? new ORPCError({
status: response.status,
code: 'INTERNAL_SERVER_ERROR',
message: 'Internal server error',
diff --git a/packages/client/src/router.test.ts b/packages/client/src/router.test.ts
index 4098b487..253ce467 100644
--- a/packages/client/src/router.test.ts
+++ b/packages/client/src/router.test.ts
@@ -113,7 +113,7 @@ describe('createRouterClient', () => {
fetch: orpcFetch,
})
- // @ts-expect-error
+ // @ts-expect-error - invalid input
expect(client.ping({ value: {} })).rejects.toThrowError(
'Validation input failed',
)
@@ -123,7 +123,7 @@ describe('createRouterClient', () => {
const router = os.router({
ping: os
.input(z.object({ value: z.date() }))
- .handler((input) => input.value),
+ .handler(input => input.value),
})
const handler = createFetchHandler({
diff --git a/packages/client/src/router.ts b/packages/client/src/router.ts
index eb37795c..2b69b593 100644
--- a/packages/client/src/router.ts
+++ b/packages/client/src/router.ts
@@ -6,7 +6,7 @@ import type {
SchemaOutput,
} from '@orpc/contract'
import type { Procedure, Promisable, Router } from '@orpc/server'
-import { type ProcedureClient, createProcedureClient } from './procedure'
+import { createProcedureClient, type ProcedureClient } from './procedure'
export type RouterClientWithContractRouter = {
[K in keyof TRouter]: TRouter[K] extends ContractProcedure<
@@ -64,10 +64,10 @@ export function createRouterClient<
>(
options: CreateRouterClientOptions,
): TRouter extends Router
- ? RouterClientWithRouter
- : TRouter extends ContractRouter
- ? RouterClientWithContractRouter
- : never {
+ ? RouterClientWithRouter
+ : TRouter extends ContractRouter
+ ? RouterClientWithContractRouter
+ : never {
const path = options?.path ?? []
const client = new Proxy(
diff --git a/packages/contract/package.json b/packages/contract/package.json
index 86930132..7cc73b1f 100644
--- a/packages/contract/package.json
+++ b/packages/contract/package.json
@@ -40,10 +40,10 @@
"build:watch": "pnpm run build --watch",
"type:check": "tsc -b"
},
- "dependencies": {
- "@orpc/shared": "workspace:*"
- },
"peerDependencies": {
"zod": "^3"
+ },
+ "dependencies": {
+ "@orpc/shared": "workspace:*"
}
}
diff --git a/packages/contract/src/builder.test.ts b/packages/contract/src/builder.test.ts
index c212f510..5223e3e2 100644
--- a/packages/contract/src/builder.test.ts
+++ b/packages/contract/src/builder.test.ts
@@ -2,7 +2,7 @@ import { z } from 'zod'
import { type DecoratedContractProcedure, oc } from '.'
describe('define a procedure', () => {
- test('use route method', () => {
+ it('use route method', () => {
const procedure = oc.route({
method: 'GET',
path: '/users/{id}',
@@ -26,7 +26,7 @@ describe('define a procedure', () => {
})
})
- test('use input method', () => {
+ it('use input method', () => {
const schema = z.object({
id: z.string(),
})
@@ -43,7 +43,7 @@ describe('define a procedure', () => {
})
})
- test('use output method', () => {
+ it('use output method', () => {
const schema = z.object({ id: z.string() })
const procedure = oc.output(schema, { id: '123' })
diff --git a/packages/contract/src/builder.ts b/packages/contract/src/builder.ts
index 1e3aac13..6604ab90 100644
--- a/packages/contract/src/builder.ts
+++ b/packages/contract/src/builder.ts
@@ -1,18 +1,18 @@
-import { DecoratedContractProcedure, type RouteOptions } from './procedure'
import type { ContractRouter } from './router'
-import { ContractRouterBuilder } from './router-builder'
import type { HTTPPath, Schema, SchemaInput, SchemaOutput } from './types'
+import { DecoratedContractProcedure, type RouteOptions } from './procedure'
+import { ContractRouterBuilder } from './router-builder'
export class ContractBuilder {
prefix(prefix: HTTPPath): ContractRouterBuilder {
return new ContractRouterBuilder({
- prefix: prefix,
+ prefix,
})
}
tags(...tags: string[]): ContractRouterBuilder {
return new ContractRouterBuilder({
- tags: tags,
+ tags,
})
}
diff --git a/packages/contract/src/procedure.test.ts b/packages/contract/src/procedure.test.ts
index 8cf5f4a0..d258902f 100644
--- a/packages/contract/src/procedure.test.ts
+++ b/packages/contract/src/procedure.test.ts
@@ -1,8 +1,8 @@
+import type { DecoratedContractProcedure } from './procedure'
import { z } from 'zod'
import { isContractProcedure, oc } from '.'
-import type { DecoratedContractProcedure } from './procedure'
-test('prefix method', () => {
+it('prefix method', () => {
const os = oc
const p1 = os.route({
method: 'GET',
@@ -17,7 +17,7 @@ test('prefix method', () => {
expect(p2.prefix('/1').prefix('/2').zz$cp.path).toEqual(undefined)
})
-test('route method', () => {
+it('route method', () => {
const p = oc
.route({
method: 'POST',
@@ -45,7 +45,7 @@ test('route method', () => {
})
})
-test('input method', () => {
+it('input method', () => {
const schema = z.string()
const p = oc.route({}).input(schema)
@@ -59,7 +59,7 @@ test('input method', () => {
})
})
-test('output method', () => {
+it('output method', () => {
const schema = z.string()
const p = oc.route({}).output(schema)
@@ -88,7 +88,7 @@ it('addTags method', () => {
expect(p3.zz$cp.tags).toEqual(['foo', 'bar', 'baz'])
})
-test('isContractProcedure function', () => {
+it('isContractProcedure function', () => {
expect(isContractProcedure(oc)).toBe(false)
expect(isContractProcedure(oc.router({}))).toBe(false)
expect(isContractProcedure(oc.route({}))).toBe(true)
diff --git a/packages/contract/src/procedure.ts b/packages/contract/src/procedure.ts
index f16f7909..69cbead8 100644
--- a/packages/contract/src/procedure.ts
+++ b/packages/contract/src/procedure.ts
@@ -42,7 +42,8 @@ export class DecoratedContractProcedure<
static decorate(
cp: ContractProcedure,
): DecoratedContractProcedure {
- if (cp instanceof DecoratedContractProcedure) return cp
+ if (cp instanceof DecoratedContractProcedure)
+ return cp
return new DecoratedContractProcedure(cp.zz$cp)
}
@@ -60,7 +61,8 @@ export class DecoratedContractProcedure<
prefix(
prefix: HTTPPath,
): DecoratedContractProcedure {
- if (!this.zz$cp.path) return this
+ if (!this.zz$cp.path)
+ return this
return new DecoratedContractProcedure({
...this.zz$cp,
@@ -71,7 +73,8 @@ export class DecoratedContractProcedure<
addTags(
...tags: string[]
): DecoratedContractProcedure {
- if (!tags.length) return this
+ if (!tags.length)
+ return this
return new DecoratedContractProcedure({
...this.zz$cp,
@@ -107,15 +110,16 @@ export type WELL_DEFINED_CONTRACT_PROCEDURE = ContractProcedure
export function isContractProcedure(
item: unknown,
): item is WELL_DEFINED_CONTRACT_PROCEDURE {
- if (item instanceof ContractProcedure) return true
+ if (item instanceof ContractProcedure)
+ return true
return (
- (typeof item === 'object' || typeof item === 'function') &&
- item !== null &&
- 'zz$cp' in item &&
- typeof item.zz$cp === 'object' &&
- item.zz$cp !== null &&
- 'InputSchema' in item.zz$cp &&
- 'OutputSchema' in item.zz$cp
+ (typeof item === 'object' || typeof item === 'function')
+ && item !== null
+ && 'zz$cp' in item
+ && typeof item.zz$cp === 'object'
+ && item.zz$cp !== null
+ && 'InputSchema' in item.zz$cp
+ && 'OutputSchema' in item.zz$cp
)
}
diff --git a/packages/contract/src/router-builder.test.ts b/packages/contract/src/router-builder.test.ts
index c1d1e354..8ace9892 100644
--- a/packages/contract/src/router-builder.test.ts
+++ b/packages/contract/src/router-builder.test.ts
@@ -2,15 +2,15 @@ import { z } from 'zod'
import { ContractProcedure, DecoratedContractProcedure, oc } from '.'
import { ContractRouterBuilder } from './router-builder'
-test('prefix method', () => {
+it('prefix method', () => {
expect(oc.prefix('/1').prefix('/2').zz$crb.prefix).toEqual('/1/2')
})
-test('tags method', () => {
+it('tags method', () => {
expect(oc.tags('1').tags('2').zz$crb.tags).toEqual(['1', '2'])
})
-test('define a router', () => {
+it('define a router', () => {
const ping = oc.route({ method: 'GET', path: '/ping' })
const pong = oc.input(z.object({ id: z.string() }))
@@ -22,11 +22,11 @@ test('define a router', () => {
.prefix('/internal')
.tags('internal')
.router({
- ping: ping,
- pong: pong,
+ ping,
+ pong,
nested: {
- ping: ping,
+ ping,
},
}),
})
diff --git a/packages/contract/src/router-builder.ts b/packages/contract/src/router-builder.ts
index 34e1ef58..994f4af2 100644
--- a/packages/contract/src/router-builder.ts
+++ b/packages/contract/src/router-builder.ts
@@ -1,9 +1,9 @@
-import { DecoratedContractProcedure, isContractProcedure } from './procedure'
import type { ContractRouter, HandledContractRouter } from './router'
import type { HTTPPath } from './types'
+import { DecoratedContractProcedure, isContractProcedure } from './procedure'
export class ContractRouterBuilder {
- constructor(public zz$crb: { prefix?: HTTPPath; tags?: string[] }) {}
+ constructor(public zz$crb: { prefix?: HTTPPath, tags?: string[] }) {}
prefix(prefix: HTTPPath): ContractRouterBuilder {
return new ContractRouterBuilder({
@@ -13,7 +13,8 @@ export class ContractRouterBuilder {
}
tags(...tags: string[]): ContractRouterBuilder {
- if (!tags.length) return this
+ if (!tags.length)
+ return this
return new ContractRouterBuilder({
...this.zz$crb,
@@ -34,7 +35,8 @@ export class ContractRouterBuilder {
handled[key] = this.zz$crb.prefix
? decorated.prefix(this.zz$crb.prefix)
: decorated
- } else {
+ }
+ else {
handled[key] = this.router(item as ContractRouter)
}
}
diff --git a/packages/contract/src/router.test.ts b/packages/contract/src/router.test.ts
index 7274d131..e4298c51 100644
--- a/packages/contract/src/router.test.ts
+++ b/packages/contract/src/router.test.ts
@@ -1,6 +1,6 @@
import { eachContractRouterLeaf, oc } from '.'
-test('each router leaf', () => {
+it('each router leaf', () => {
const router = {
ping: oc.route({
method: 'GET',
diff --git a/packages/contract/src/router.ts b/packages/contract/src/router.ts
index 2943a25f..ddd1a67b 100644
--- a/packages/contract/src/router.ts
+++ b/packages/contract/src/router.ts
@@ -1,8 +1,8 @@
import {
type ContractProcedure,
type DecoratedContractProcedure,
- type WELL_DEFINED_CONTRACT_PROCEDURE,
isContractProcedure,
+ type WELL_DEFINED_CONTRACT_PROCEDURE,
} from './procedure'
export interface ContractRouter {
@@ -30,7 +30,8 @@ export function eachContractRouterLeaf(
if (isContractProcedure(item)) {
callback(item, [...prefix, key])
- } else {
+ }
+ else {
eachContractRouterLeaf(item as ContractRouter, callback, [...prefix, key])
}
}
diff --git a/packages/contract/src/types.test-d.ts b/packages/contract/src/types.test-d.ts
index 6e64acb8..db0503e8 100644
--- a/packages/contract/src/types.test-d.ts
+++ b/packages/contract/src/types.test-d.ts
@@ -1,5 +1,5 @@
-import { z } from 'zod'
import type { SchemaInput, SchemaOutput } from './types'
+import { z } from 'zod'
test('SchemaInput', () => {
const schema = z.string()
@@ -9,7 +9,7 @@ test('SchemaInput', () => {
})
test('SchemaOutput', () => {
- const schema = z.string().transform((v) => Number.parseFloat(v))
+ const schema = z.string().transform(v => Number.parseFloat(v))
expectTypeOf>().toEqualTypeOf()
expectTypeOf>().toEqualTypeOf()
diff --git a/packages/contract/src/types.ts b/packages/contract/src/types.ts
index 57314859..23bc2374 100644
--- a/packages/contract/src/types.ts
+++ b/packages/contract/src/types.ts
@@ -1,4 +1,4 @@
-import type { ZodType, input, output } from 'zod'
+import type { input, output, ZodType } from 'zod'
export type HTTPPath = `/${string}`
export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
diff --git a/packages/contract/src/utils.test.ts b/packages/contract/src/utils.test.ts
index 4f2819fd..182bd42a 100644
--- a/packages/contract/src/utils.test.ts
+++ b/packages/contract/src/utils.test.ts
@@ -1,13 +1,13 @@
import { prefixHTTPPath, standardizeHTTPPath } from './utils'
-test('standardizeHTTPPath', () => {
+it('standardizeHTTPPath', () => {
expect(standardizeHTTPPath('/abc')).toBe('/abc')
expect(standardizeHTTPPath('/abc/')).toBe('/abc')
expect(standardizeHTTPPath('/abc//')).toBe('/abc')
expect(standardizeHTTPPath('//abc//')).toBe('/abc')
})
-test('prefixHTTPPath', () => {
+it('prefixHTTPPath', () => {
expect(prefixHTTPPath('/', '/abc')).toBe('/abc')
expect(prefixHTTPPath('/', '/abc/')).toBe('/abc')
expect(prefixHTTPPath('/', '/abc//')).toBe('/abc')
diff --git a/packages/contract/src/utils.ts b/packages/contract/src/utils.ts
index 869df062..aa11fd63 100644
--- a/packages/contract/src/utils.ts
+++ b/packages/contract/src/utils.ts
@@ -8,8 +8,10 @@ export function prefixHTTPPath(prefix: HTTPPath, path: HTTPPath): HTTPPath {
const prefix_ = standardizeHTTPPath(prefix)
const path_ = standardizeHTTPPath(path)
- if (prefix_ === '/') return path_
- if (path_ === '/') return prefix_
+ if (prefix_ === '/')
+ return path_
+ if (path_ === '/')
+ return prefix_
return `${prefix_}${path_}`
}
diff --git a/packages/openapi/package.json b/packages/openapi/package.json
index 56f3e96e..2e2ab124 100644
--- a/packages/openapi/package.json
+++ b/packages/openapi/package.json
@@ -40,10 +40,6 @@
"build:watch": "pnpm run build --watch",
"type:check": "tsc -b"
},
- "devDependencies": {
- "@readme/openapi-parser": "^2.6.0",
- "zod": "^3.23.8"
- },
"dependencies": {
"@orpc/contract": "workspace:*",
"@orpc/server": "workspace:*",
@@ -53,5 +49,9 @@
"escape-string-regexp": "^5.0.0",
"json-schema-typed": "^8.0.1",
"openapi3-ts": "^4.4.0"
+ },
+ "devDependencies": {
+ "@readme/openapi-parser": "^2.6.0",
+ "zod": "^3.23.8"
}
}
diff --git a/packages/openapi/src/generator.test.ts b/packages/openapi/src/generator.test.ts
index a1ae4871..bbae37e5 100644
--- a/packages/openapi/src/generator.test.ts
+++ b/packages/openapi/src/generator.test.ts
@@ -1,6 +1,6 @@
+import type { OpenAPIObject } from 'openapi3-ts/oas31'
import { oc } from '@orpc/contract'
import { oz } from '@orpc/zod'
-import type { OpenAPIObject } from 'openapi3-ts/oas31'
import { z } from 'zod'
import { generateOpenAPI } from './generator'
@@ -36,7 +36,7 @@ it('works', () => {
'/ping': {
post: {
responses: {
- '200': {
+ 200: {
description: 'OK',
content: {
'application/json': {
@@ -63,7 +63,7 @@ it('works', () => {
},
],
responses: {
- '200': {
+ 200: {
description: 'OK',
content: {
'application/json': {
@@ -133,7 +133,7 @@ it('throwOnMissingTagDefinition option', () => {
'/ping': {
post: {
responses: {
- '200': {
+ 200: {
description: 'OK',
content: {
'application/json': {
@@ -160,7 +160,7 @@ it('throwOnMissingTagDefinition option', () => {
},
],
responses: {
- '200': {
+ 200: {
description: 'OK',
content: {
'application/json': {
@@ -237,7 +237,7 @@ it('support single file upload', () => {
},
},
responses: {
- '200': {
+ 200: {
content: {
'image/jpg': {
schema: {
@@ -310,7 +310,7 @@ it('support multipart/form-data', () => {
},
},
responses: {
- '200': {
+ 200: {
content: {
'image/*': {
schema: {
@@ -415,7 +415,7 @@ it('work with example', () => {
},
},
responses: {
- '200': {
+ 200: {
content: {
'application/json': {
schema: {
@@ -527,7 +527,7 @@ it('should remove params on body', () => {
},
},
responses: {
- '200': {
+ 200: {
description: 'OK',
content: {
'application/json': { schema: {}, example: undefined },
@@ -629,7 +629,7 @@ it('should remove params on query', () => {
],
requestBody: undefined,
responses: {
- '200': {
+ 200: {
description: 'OK',
content: {
'application/json': { schema: {}, example: undefined },
diff --git a/packages/openapi/src/generator.ts b/packages/openapi/src/generator.ts
index f5a6a7f6..c3fa5489 100644
--- a/packages/openapi/src/generator.ts
+++ b/packages/openapi/src/generator.ts
@@ -1,20 +1,20 @@
+import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
import { type ContractRouter, eachContractRouterLeaf } from '@orpc/contract'
import { type Router, toContractRouter } from '@orpc/server'
import { findDeepMatches, isPlainObject, omit } from '@orpc/shared'
import { preSerialize } from '@orpc/transformer'
-import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
import {
type MediaTypeObject,
- type OpenAPIObject,
OpenApiBuilder,
+ type OpenAPIObject,
type OperationObject,
type ParameterObject,
type RequestBodyObject,
type ResponseObject,
} from 'openapi3-ts/oas31'
import {
- UNSUPPORTED_JSON_SCHEMA,
extractJSONSchema,
+ UNSUPPORTED_JSON_SCHEMA,
zodToJsonSchema,
} from './zod-to-json-schema'
@@ -45,17 +45,17 @@ export function generateOpenAPI(
} & Omit,
options?: GenerateOpenAPIOptions,
): OpenAPIObject {
- const throwOnMissingTagDefinition =
- options?.throwOnMissingTagDefinition ?? false
- const ignoreUndefinedPathProcedures =
- options?.ignoreUndefinedPathProcedures ?? false
+ const throwOnMissingTagDefinition
+ = options?.throwOnMissingTagDefinition ?? false
+ const ignoreUndefinedPathProcedures
+ = options?.ignoreUndefinedPathProcedures ?? false
const builder = new OpenApiBuilder({
...omit(opts, ['router']),
openapi: '3.1.0',
})
- const rootTags = opts.tags?.map((tag) => tag.name) ?? []
+ const rootTags = opts.tags?.map(tag => tag.name) ?? []
const router = toContractRouter(opts.router)
eachContractRouterLeaf(router, (procedure, path_) => {
@@ -76,7 +76,7 @@ export function generateOpenAPI(
: {}
const params: ParameterObject[] | undefined = (() => {
- const names = path.match(/{([^}]+)}/g)
+ const names = path.match(/\{([^}]+)\}/g)
if (!names || !names.length) {
return undefined
@@ -89,7 +89,7 @@ export function generateOpenAPI(
}
return names
- .map((raw) => raw.slice(1, -1))
+ .map(raw => raw.slice(1, -1))
.map((name) => {
let schema = inputSchema.properties?.[name]
const required = inputSchema.required?.includes(name)
@@ -127,19 +127,20 @@ export function generateOpenAPI(
...inputSchema,
properties: inputSchema.properties
? Object.entries(inputSchema.properties).reduce(
- (acc, [key, value]) => {
- if (key !== name) {
- acc[key] = value
- }
-
- return acc
- },
- {} as Record,
- )
+ (acc, [key, value]) => {
+ if (key !== name) {
+ acc[key] = value
+ }
+
+ return acc
+ },
+ {} as Record,
+ )
: undefined,
- required: inputSchema.required?.filter((v) => v !== name),
+ required: inputSchema.required?.filter(v => v !== name),
examples: inputSchema.examples?.map((example) => {
- if (!isPlainObject(example)) return example
+ if (!isPlainObject(example))
+ return example
return Object.entries(example).reduce(
(acc, [key, value]) => {
@@ -220,8 +221,8 @@ export function generateOpenAPI(
contentMediaType: string
})[]
- const isStillHasFileSchema =
- findDeepMatches(isFileSchema, schema).values.length > 0
+ const isStillHasFileSchema
+ = findDeepMatches(isFileSchema, schema).values.length > 0
if (files.length) {
parameters.push({
@@ -268,8 +269,8 @@ export function generateOpenAPI(
contentMediaType: string
})[]
- const isStillHasFileSchema =
- findDeepMatches(isFileSchema, schema).values.length > 0
+ const isStillHasFileSchema
+ = findDeepMatches(isFileSchema, schema).values.length > 0
const content: Record = {}
@@ -295,7 +296,7 @@ export function generateOpenAPI(
})()
if (throwOnMissingTagDefinition && internal.tags) {
- const missingTag = internal.tags.find((tag) => !rootTags.includes(tag))
+ const missingTag = internal.tags.find(tag => !rootTags.includes(tag))
if (missingTag !== undefined) {
throw new Error(
@@ -313,7 +314,7 @@ export function generateOpenAPI(
parameters: parameters.length ? parameters : undefined,
requestBody,
responses: {
- '200': successResponse,
+ 200: successResponse,
},
}
@@ -326,11 +327,12 @@ export function generateOpenAPI(
}
function isFileSchema(schema: unknown) {
- if (typeof schema !== 'object' || schema === null) return false
+ if (typeof schema !== 'object' || schema === null)
+ return false
return (
- 'type' in schema &&
- 'contentMediaType' in schema &&
- typeof schema.type === 'string' &&
- typeof schema.contentMediaType === 'string'
+ 'type' in schema
+ && 'contentMediaType' in schema
+ && typeof schema.type === 'string'
+ && typeof schema.contentMediaType === 'string'
)
}
diff --git a/packages/openapi/src/zod-to-json-schema.test.ts b/packages/openapi/src/zod-to-json-schema.test.ts
index 91ba392b..415ff2ac 100644
--- a/packages/openapi/src/zod-to-json-schema.test.ts
+++ b/packages/openapi/src/zod-to-json-schema.test.ts
@@ -244,7 +244,7 @@ describe('special types', () => {
describe('transform and effects', () => {
it('should handle transform effects based on mode', () => {
- const schema = z.string().transform((val) => val.length)
+ const schema = z.string().transform(val => val.length)
expect(zodToJsonSchema(schema, { mode: 'input' })).toEqual({
type: 'string',
diff --git a/packages/openapi/src/zod-to-json-schema.ts b/packages/openapi/src/zod-to-json-schema.ts
index b1d21089..9c90d5fa 100644
--- a/packages/openapi/src/zod-to-json-schema.ts
+++ b/packages/openapi/src/zod-to-json-schema.ts
@@ -14,11 +14,8 @@ import {
type KeySchema,
type ZodAny,
type ZodArray,
- type ZodBigInt,
- type ZodBoolean,
type ZodBranded,
type ZodCatch,
- type ZodDate,
type ZodDefault,
type ZodDiscriminatedUnion,
type ZodEffects,
@@ -28,7 +25,6 @@ import {
type ZodLazy,
type ZodLiteral,
type ZodMap,
- type ZodNaN,
type ZodNativeEnum,
type ZodNullable,
type ZodNumber,
@@ -213,8 +209,8 @@ export function zodToJsonSchema(
json.pattern = `${escapeStringRegexp(check.value)}$`
break
case 'emoji':
- json.pattern =
- '^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$'
+ json.pattern
+ = '^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$'
break
case 'nanoid':
json.pattern = '^[a-zA-Z0-9_-]{21}$'
@@ -278,14 +274,10 @@ export function zodToJsonSchema(
}
case ZodFirstPartyTypeKind.ZodNaN: {
- const schema_ = schema as ZodNaN
-
return { const: 'NaN' }
}
case ZodFirstPartyTypeKind.ZodBigInt: {
- const schema_ = schema as ZodBigInt
-
const json: JSONSchema = { type: 'string', pattern: '^-?[0-9]+$' }
// WARN: ignore checks
@@ -294,14 +286,10 @@ export function zodToJsonSchema(
}
case ZodFirstPartyTypeKind.ZodBoolean: {
- const schema_ = schema as ZodBoolean
-
return { type: 'boolean' }
}
case ZodFirstPartyTypeKind.ZodDate: {
- const schema_ = schema as ZodDate
-
const jsonSchema: JSONSchema = { type: 'string', format: Format.Date }
// WARN: ignore checks
@@ -398,7 +386,7 @@ export function zodToJsonSchema(
for (const [key, value] of Object.entries(schema_.shape)) {
const { schema, matches } = extractJSONSchema(
zodToJsonSchema(value, childOptions),
- (schema) => schema === UNDEFINED_JSON_SCHEMA,
+ schema => schema === UNDEFINED_JSON_SCHEMA,
)
if (schema) {
@@ -423,14 +411,15 @@ export function zodToJsonSchema(
childOptions,
)
if (schema_._def.unknownKeys === 'strict') {
- json.additionalProperties =
- additionalProperties === UNSUPPORTED_JSON_SCHEMA
+ json.additionalProperties
+ = additionalProperties === UNSUPPORTED_JSON_SCHEMA
? false
: additionalProperties
- } else {
+ }
+ else {
if (
- additionalProperties &&
- additionalProperties !== UNSUPPORTED_JSON_SCHEMA
+ additionalProperties
+ && additionalProperties !== UNSUPPORTED_JSON_SCHEMA
) {
json.additionalProperties = additionalProperties
}
@@ -551,8 +540,8 @@ export function zodToJsonSchema(
const schema_ = schema as ZodEffects
if (
- schema_._def.effect.type === 'transform' &&
- childOptions?.mode === 'output'
+ schema_._def.effect.type === 'transform'
+ && childOptions?.mode === 'output'
) {
return {}
}
@@ -602,7 +591,7 @@ export function extractJSONSchema(
schema: JSONSchema,
check: (schema: JSONSchema) => boolean,
matches: JSONSchema[] = [],
-): { schema: JSONSchema | undefined; matches: JSONSchema[] } {
+): { schema: JSONSchema | undefined, matches: JSONSchema[] } {
if (check(schema)) {
matches.push(schema)
return { schema: undefined, matches }
@@ -615,14 +604,14 @@ export function extractJSONSchema(
// TODO: $ref
if (
- schema.anyOf &&
- Object.keys(schema).every(
- (k) => k === 'anyOf' || NON_LOGIC_KEYWORDS.includes(k as any),
+ schema.anyOf
+ && Object.keys(schema).every(
+ k => k === 'anyOf' || NON_LOGIC_KEYWORDS.includes(k as any),
)
) {
const anyOf = schema.anyOf
- .map((s) => extractJSONSchema(s, check, matches).schema)
- .filter((v) => !!v)
+ .map(s => extractJSONSchema(s, check, matches).schema)
+ .filter(v => !!v)
if (anyOf.length === 1 && typeof anyOf[0] === 'object') {
return { schema: { ...schema, anyOf: undefined, ...anyOf[0] }, matches }
@@ -640,14 +629,14 @@ export function extractJSONSchema(
// TODO: $ref
if (
- schema.oneOf &&
- Object.keys(schema).every(
- (k) => k === 'oneOf' || NON_LOGIC_KEYWORDS.includes(k as any),
+ schema.oneOf
+ && Object.keys(schema).every(
+ k => k === 'oneOf' || NON_LOGIC_KEYWORDS.includes(k as any),
)
) {
const oneOf = schema.oneOf
- .map((s) => extractJSONSchema(s, check, matches).schema)
- .filter((v) => !!v)
+ .map(s => extractJSONSchema(s, check, matches).schema)
+ .filter(v => !!v)
if (oneOf.length === 1 && typeof oneOf[0] === 'object') {
return { schema: { ...schema, oneOf: undefined, ...oneOf[0] }, matches }
diff --git a/packages/openapi/vitest.setup.ts b/packages/openapi/vitest.setup.ts
index a176ae3e..4eb22dfc 100644
--- a/packages/openapi/vitest.setup.ts
+++ b/packages/openapi/vitest.setup.ts
@@ -1,12 +1,13 @@
+import type { generateOpenAPI } from './src/generator'
import OpenAPIParser from '@readme/openapi-parser'
import { expect, vi } from 'vitest'
-import type { generateOpenAPI } from './src/generator'
+// eslint-disable-next-line antfu/no-top-level-await
const generator = await vi.importActual('./src/generator')
vi.mock('./src/generator', () => ({
generateOpenAPI: vi.fn((...args) => {
- // @ts-expect-error
+ // @ts-expect-error - untyped
const spec = generator.generateOpenAPI(...args)
expect(
(async () => {
diff --git a/packages/react/package.json b/packages/react/package.json
index 8f6665d7..29e42a8b 100644
--- a/packages/react/package.json
+++ b/packages/react/package.json
@@ -40,16 +40,16 @@
"build:watch": "pnpm run build --watch",
"type:check": "tsc -b"
},
- "dependencies": {
- "@orpc/client": "workspace:*",
- "@orpc/shared": "workspace:*"
- },
"peerDependencies": {
"@orpc/contract": "workspace:*",
"@orpc/server": "workspace:*",
"@tanstack/react-query": "^5.59.9",
"react": "^18.3.1"
},
+ "dependencies": {
+ "@orpc/client": "workspace:*",
+ "@orpc/shared": "workspace:*"
+ },
"devDependencies": {
"@tanstack/react-query": "^5.59.9",
"react": "^18.3.1",
diff --git a/packages/react/src/general-hooks.test.tsx b/packages/react/src/general-hooks.test.tsx
index 04cf2a8f..e0fa1408 100644
--- a/packages/react/src/general-hooks.test.tsx
+++ b/packages/react/src/general-hooks.test.tsx
@@ -3,10 +3,10 @@ import { useMutation, useQuery } from '@tanstack/react-query'
import { renderHook } from '@testing-library/react'
import {
ORPCContext,
+ queryClient,
type UserCreateInputSchema,
type UserFindInputSchema,
type UserSchema,
- queryClient,
wrapper,
} from '../tests/orpc'
import { createGeneralHooks } from './general-hooks'
@@ -72,7 +72,7 @@ describe('useIsFetching', () => {
{ input: { id: '12333' }, type: 'query' },
],
queryFn: async () => {
- await new Promise((resolve) => setTimeout(resolve, 100))
+ await new Promise(resolve => setTimeout(resolve, 100))
},
},
queryClient,
@@ -86,14 +86,14 @@ describe('useIsFetching', () => {
{ input: { id: '12333' }, type: 'infinite' },
],
queryFn: async () => {
- await new Promise((resolve) => setTimeout(resolve, 100))
+ await new Promise(resolve => setTimeout(resolve, 100))
},
},
queryClient,
),
)
- await new Promise((resolve) => setTimeout(resolve, 50)) // < 100 make sure the query is not finished
+ await new Promise(resolve => setTimeout(resolve, 50)) // < 100 make sure the query is not finished
expect(result.current).toBe(2)
expect(result2.current).toBe(2)
@@ -147,7 +147,7 @@ describe('useIsMutating', () => {
{
mutationKey: [['user', 'create']],
mutationFn: async () => {
- await new Promise((resolve) => setTimeout(resolve, 100))
+ await new Promise(resolve => setTimeout(resolve, 100))
},
},
queryClient,
@@ -156,7 +156,7 @@ describe('useIsMutating', () => {
mutation.current.mutate()
- await new Promise((resolve) => setTimeout(resolve, 50)) // < 100 make sure the query is not finished
+ await new Promise(resolve => setTimeout(resolve, 50)) // < 100 make sure the query is not finished
expect(result.current).toBe(1)
expect(result2.current).toBe(0)
@@ -210,7 +210,7 @@ describe('useMutationState', () => {
{
mutationKey: [['user', 'create']],
mutationFn: async () => {
- await new Promise((resolve) => setTimeout(resolve, 100))
+ await new Promise(resolve => setTimeout(resolve, 100))
},
},
queryClient,
@@ -219,7 +219,7 @@ describe('useMutationState', () => {
mutation.current.mutate({ name: 'unnoq' } as any)
- await new Promise((resolve) => setTimeout(resolve, 50)) // < 100 make sure the query is not finished
+ await new Promise(resolve => setTimeout(resolve, 50)) // < 100 make sure the query is not finished
expect(result.current.length).toBe(1)
expect(result2.current.length).toBe(0)
diff --git a/packages/react/src/general-hooks.ts b/packages/react/src/general-hooks.ts
index 34cc43f6..b7b4aab6 100644
--- a/packages/react/src/general-hooks.ts
+++ b/packages/react/src/general-hooks.ts
@@ -1,5 +1,6 @@
import type { Schema, SchemaInput, SchemaOutput } from '@orpc/contract'
import type { PartialDeep, SetOptional } from '@orpc/shared'
+import type { ORPCQueryFilters } from './tanstack-query'
import {
type DefaultError,
type Mutation,
@@ -11,19 +12,18 @@ import {
} from '@tanstack/react-query'
import { type ORPCContext, useORPCContext } from './react-context'
import { getMutationKeyFromPath, getQueryKeyFromPath } from './tanstack-key'
-import type { ORPCQueryFilters } from './tanstack-query'
export interface GeneralHooks<
TInputSchema extends Schema,
TOutputSchema extends Schema,
THandlerOutput extends SchemaOutput,
> {
- useIsFetching(
+ useIsFetching: (
filers?: ORPCQueryFilters>>,
- ): number
- useIsMutating(filters?: SetOptional): number
+ ) => number
+ useIsMutating: (filters?: SetOptional) => number
- useMutationState<
+ useMutationState: <
UResult = MutationState<
SchemaOutput,
DefaultError,
@@ -38,7 +38,8 @@ export interface GeneralHooks<
SchemaInput
>,
) => UResult
- }): UResult[]
+ }
+ ) => UResult[]
}
export interface CreateGeneralHooksOptions {
@@ -56,7 +57,7 @@ export function createGeneralHooks<
TInputSchema extends Schema = undefined,
TOutputSchema extends Schema = undefined,
THandlerOutput extends
- SchemaOutput = SchemaOutput,
+ SchemaOutput = SchemaOutput,
>(
options: CreateGeneralHooksOptions,
): GeneralHooks {
diff --git a/packages/react/src/general-utils.test-d.ts b/packages/react/src/general-utils.test-d.ts
index e8a22a4a..2a10b841 100644
--- a/packages/react/src/general-utils.test-d.ts
+++ b/packages/react/src/general-utils.test-d.ts
@@ -2,17 +2,17 @@ import type { SchemaOutput } from '@orpc/contract'
import type { Promisable } from '@orpc/shared'
import type { InfiniteData } from '@tanstack/react-query'
import {
+ queryClient,
type UserCreateInputSchema,
type UserFindInputSchema,
type UserListInputSchema,
type UserListOutputSchema,
type UserSchema,
- queryClient,
} from '../tests/orpc'
import { createGeneralUtils } from './general-utils'
const user_utils = createGeneralUtils({
- queryClient: queryClient,
+ queryClient,
path: ['user'],
})
@@ -21,7 +21,7 @@ const user_find_utils = createGeneralUtils<
typeof UserSchema,
SchemaOutput
>({
- queryClient: queryClient,
+ queryClient,
path: ['user', 'find'],
})
@@ -30,7 +30,7 @@ const user_list_utils = createGeneralUtils<
typeof UserListOutputSchema,
SchemaOutput
>({
- queryClient: queryClient,
+ queryClient,
path: ['user', 'list'],
})
@@ -39,7 +39,7 @@ const user_create_utils = createGeneralUtils<
typeof UserSchema,
SchemaOutput
>({
- queryClient: queryClient,
+ queryClient,
path: ['user', 'create'],
})
@@ -121,9 +121,9 @@ describe('setInfiniteQueriesData', () => {
user_list_utils.setInfiniteQueriesData({}, (old) => {
expectTypeOf(old).toEqualTypeOf<
| InfiniteData<
- SchemaOutput,
+ SchemaOutput,
number | undefined
- >
+ >
| undefined
>()
diff --git a/packages/react/src/general-utils.test.tsx b/packages/react/src/general-utils.test.tsx
index aa61efda..78542b0d 100644
--- a/packages/react/src/general-utils.test.tsx
+++ b/packages/react/src/general-utils.test.tsx
@@ -1,11 +1,4 @@
import type { SchemaOutput } from '@orpc/contract'
-import {
- QueryClient,
- useInfiniteQuery,
- useMutation,
- useQuery,
-} from '@tanstack/react-query'
-import { renderHook } from '@testing-library/react'
import type {
UserCreateInputSchema,
UserFindInputSchema,
@@ -13,6 +6,13 @@ import type {
UserListOutputSchema,
UserSchema,
} from '../tests/orpc'
+import {
+ QueryClient,
+ useInfiniteQuery,
+ useMutation,
+ useQuery,
+} from '@tanstack/react-query'
+import { renderHook } from '@testing-library/react'
import { createGeneralUtils } from './general-utils'
let qc = new QueryClient()
@@ -299,8 +299,8 @@ describe('refetch', () => {
const infiniteQueryKey = [['user', 'list'], { type: 'infinite' }]
const queryKey = [['user', 'list'], { type: 'query' }]
- const fn1 = vi.fn(() => new Promise((resolve) => setTimeout(resolve, 100)))
- const fn2 = vi.fn(() => new Promise((resolve) => setTimeout(resolve, 100)))
+ const fn1 = vi.fn(() => new Promise(resolve => setTimeout(resolve, 100)))
+ const fn2 = vi.fn(() => new Promise(resolve => setTimeout(resolve, 100)))
beforeEach(() => {
fn1.mockClear()
@@ -321,7 +321,7 @@ describe('refetch', () => {
renderHook(() =>
useQuery(
{
- queryKey: queryKey,
+ queryKey,
queryFn: fn2,
},
qc,
@@ -338,7 +338,7 @@ describe('refetch', () => {
expect(fn1).toHaveBeenCalledTimes(1)
expect(fn2).toHaveBeenCalledTimes(1)
- await new Promise((resolve) => setTimeout(resolve, 101))
+ await new Promise(resolve => setTimeout(resolve, 101))
user_utils.refetch()
expect(fn1).toHaveBeenCalledTimes(2)
@@ -350,7 +350,7 @@ describe('refetch', () => {
expect(fn1).toHaveBeenCalledTimes(1)
expect(fn2).toHaveBeenCalledTimes(1)
- await new Promise((resolve) => setTimeout(resolve, 101))
+ await new Promise(resolve => setTimeout(resolve, 101))
user_utils.refetch({ queryType: 'query' })
expect(fn1).toHaveBeenCalledTimes(1)
@@ -363,7 +363,7 @@ describe('refetch', () => {
expect(fn1).toHaveBeenCalledTimes(1)
expect(fn2).toHaveBeenCalledTimes(1)
- await new Promise((resolve) => setTimeout(resolve, 101))
+ await new Promise(resolve => setTimeout(resolve, 101))
user_list_utils.refetch()
expect(fn1).toHaveBeenCalledTimes(2)
@@ -376,7 +376,7 @@ describe('refetch', () => {
expect(fn1).toHaveBeenCalledTimes(1)
expect(fn2).toHaveBeenCalledTimes(1)
- await new Promise((resolve) => setTimeout(resolve, 101))
+ await new Promise(resolve => setTimeout(resolve, 101))
user_list_utils.refetch({ queryType: 'infinite' })
expect(fn1).toHaveBeenCalledTimes(2)
@@ -389,7 +389,7 @@ describe('refetch', () => {
expect(fn1).toHaveBeenCalledTimes(1)
expect(fn2).toHaveBeenCalledTimes(1)
- await new Promise((resolve) => setTimeout(resolve, 101))
+ await new Promise(resolve => setTimeout(resolve, 101))
user_find_utils.refetch()
expect(fn1).toHaveBeenCalledTimes(1)
@@ -407,7 +407,7 @@ describe('cancel', () => {
{
queryKey: infiniteQueryKey,
queryFn: async () =>
- await new Promise((resolve) => setTimeout(resolve, 100)),
+ await new Promise(resolve => setTimeout(resolve, 100)),
getNextPageParam: () => 2,
initialPageParam: 1,
},
@@ -418,9 +418,9 @@ describe('cancel', () => {
renderHook(() =>
useQuery(
{
- queryKey: queryKey,
+ queryKey,
queryFn: async () =>
- await new Promise((resolve) => setTimeout(resolve, 100)),
+ await new Promise(resolve => setTimeout(resolve, 100)),
},
qc,
),
@@ -516,8 +516,8 @@ describe('reset', () => {
const infiniteQueryKey = [['user', 'list'], { type: 'infinite' }]
const queryKey = [['user', 'list'], { type: 'query' }]
- const fn1 = vi.fn(() => new Promise((resolve) => setTimeout(resolve, 100)))
- const fn2 = vi.fn(() => new Promise((resolve) => setTimeout(resolve, 100)))
+ const fn1 = vi.fn(() => new Promise(resolve => setTimeout(resolve, 100)))
+ const fn2 = vi.fn(() => new Promise(resolve => setTimeout(resolve, 100)))
beforeEach(() => {
fn1.mockClear()
@@ -538,7 +538,7 @@ describe('reset', () => {
renderHook(() =>
useQuery(
{
- queryKey: queryKey,
+ queryKey,
queryFn: fn2,
},
qc,
@@ -594,7 +594,7 @@ it('isFetching', () => {
{
queryKey: infiniteQueryKey,
queryFn: async () =>
- await new Promise((resolve) => setTimeout(resolve, 100)),
+ await new Promise(resolve => setTimeout(resolve, 100)),
getNextPageParam: () => 2,
initialPageParam: 1,
},
@@ -605,9 +605,9 @@ it('isFetching', () => {
renderHook(() =>
useQuery(
{
- queryKey: queryKey,
+ queryKey,
queryFn: async () =>
- await new Promise((resolve) => setTimeout(resolve, 100)),
+ await new Promise(resolve => setTimeout(resolve, 100)),
},
qc,
),
@@ -630,7 +630,7 @@ it('isMutating', async () => {
useMutation(
{
mutationKey: [['user', 'create']],
- mutationFn: () => new Promise((resolve) => setTimeout(resolve, 100)),
+ mutationFn: () => new Promise(resolve => setTimeout(resolve, 100)),
},
qc,
),
diff --git a/packages/react/src/general-utils.ts b/packages/react/src/general-utils.ts
index 26f9baca..4caed91f 100644
--- a/packages/react/src/general-utils.ts
+++ b/packages/react/src/general-utils.ts
@@ -16,41 +16,39 @@ import type {
SetDataOptions,
Updater,
} from '@tanstack/react-query'
-import { getMutationKeyFromPath, getQueryKeyFromPath } from './tanstack-key'
import type {
ORPCInvalidateQueryFilters,
ORPCQueryFilters,
} from './tanstack-query'
import type { SchemaInputForInfiniteQuery } from './types'
+import { getMutationKeyFromPath, getQueryKeyFromPath } from './tanstack-key'
export interface GeneralUtils<
TInputSchema extends Schema,
TOutputSchema extends Schema,
THandlerOutput extends SchemaOutput,
> {
- getQueriesData(
+ getQueriesData: (
filters?: OmitKeyof<
ORPCQueryFilters>>,
'queryType'
>,
- ): [QueryKey, SchemaOutput | undefined][]
- getInfiniteQueriesData(
+ ) => [QueryKey, SchemaOutput | undefined][]
+ getInfiniteQueriesData: (
filters?: OmitKeyof<
ORPCQueryFilters>>,
'queryType'
>,
- ): [
+ ) => [
QueryKey,
- (
- | InfiniteData<
- SchemaOutput,
- SchemaInput['cursor']
- >
- | undefined
- ),
+ | undefined
+ | InfiniteData<
+ SchemaOutput,
+ SchemaInput['cursor']
+ >,
][]
- setQueriesData(
+ setQueriesData: (
filters: OmitKeyof<
ORPCQueryFilters>>,
'queryType'
@@ -60,78 +58,76 @@ export interface GeneralUtils<
SchemaOutput | undefined
>,
options?: SetDataOptions,
- ): [QueryKey, SchemaOutput | undefined][]
- setInfiniteQueriesData(
+ ) => [QueryKey, SchemaOutput | undefined][]
+ setInfiniteQueriesData: (
filters: OmitKeyof<
ORPCQueryFilters>>,
'queryType'
>,
updater: Updater<
| InfiniteData<
- SchemaOutput,
- SchemaInput['cursor']
- >
+ SchemaOutput,
+ SchemaInput['cursor']
+ >
| undefined,
| InfiniteData<
- SchemaOutput,
- SchemaInput['cursor']
- >
+ SchemaOutput,
+ SchemaInput['cursor']
+ >
| undefined
>,
options?: SetDataOptions,
- ): [
+ ) => [
QueryKey,
- (
- | InfiniteData<
- SchemaOutput,
- SchemaInput['cursor']
- >
- | undefined
- ),
+ | undefined
+ | InfiniteData<
+ SchemaOutput,
+ SchemaInput['cursor']
+ >,
][]
- invalidate(
+ invalidate: (
filters?: ORPCInvalidateQueryFilters<
PartialDeep>
>,
options?: InvalidateOptions,
- ): Promise
- refetch(
+ ) => Promise
+ refetch: (
filters?: ORPCQueryFilters>>,
options?: RefetchOptions,
- ): Promise
- cancel(
+ ) => Promise
+ cancel: (
filters?: ORPCQueryFilters>>,
options?: CancelOptions,
- ): Promise
- remove(
+ ) => Promise
+ remove: (
filters?: ORPCQueryFilters>>,
- ): void
- reset(
+ ) => void
+ reset: (
filters?: ORPCQueryFilters>>,
options?: ResetOptions,
- ): Promise
+ ) => Promise
- isFetching(
+ isFetching: (
filters?: ORPCQueryFilters>>,
- ): number
- isMutating(filters?: SetOptional): number
+ ) => number
+ isMutating: (filters?: SetOptional) => number
- getQueryDefaults(
+ getQueryDefaults: (
filters?: Pick<
ORPCQueryFilters>>,
'input' | 'queryKey'
>,
- ): OmitKeyof<
+ ) => OmitKeyof<
QueryObserverOptions>,
'queryKey'
>
- getInfiniteQueryDefaults(
+ getInfiniteQueryDefaults: (
filters?: Pick<
ORPCQueryFilters>>,
'input' | 'queryKey'
>,
- ): OmitKeyof<
+ ) => OmitKeyof<
QueryObserverOptions<
SchemaOutput,
DefaultError,
@@ -143,7 +139,7 @@ export interface GeneralUtils<
'queryKey'
>
- setQueryDefaults(
+ setQueryDefaults: (
options: Partial<
OmitKeyof<
QueryObserverOptions>,
@@ -154,8 +150,8 @@ export interface GeneralUtils<
ORPCQueryFilters>>,
'input' | 'queryKey'
>,
- ): void
- setInfiniteQueryDefaults(
+ ) => void
+ setInfiniteQueryDefaults: (
options: Partial<
OmitKeyof<
QueryObserverOptions<
@@ -173,7 +169,7 @@ export interface GeneralUtils<
ORPCQueryFilters>>,
'input' | 'queryKey'
>,
- ): void
+ ) => void
getMutationDefaults: (
filters?: Pick,
@@ -210,7 +206,7 @@ export function createGeneralUtils<
TInputSchema extends Schema = undefined,
TOutputSchema extends Schema = undefined,
THandlerOutput extends
- SchemaOutput = SchemaOutput,
+ SchemaOutput = SchemaOutput,
>(
options: CreateGeneralUtilsOptions,
): GeneralUtils {
@@ -344,40 +340,40 @@ export function createGeneralUtils<
getQueryDefaults(filters) {
return options.queryClient.getQueryDefaults(
- filters?.queryKey ??
- getQueryKeyFromPath(options.path, {
- input: filters?.input,
- type: 'query',
- }),
+ filters?.queryKey
+ ?? getQueryKeyFromPath(options.path, {
+ input: filters?.input,
+ type: 'query',
+ }),
)
},
getInfiniteQueryDefaults(filters) {
return options.queryClient.getQueryDefaults(
- filters?.queryKey ??
- getQueryKeyFromPath(options.path, {
- input: filters?.input,
- type: 'infinite',
- }),
+ filters?.queryKey
+ ?? getQueryKeyFromPath(options.path, {
+ input: filters?.input,
+ type: 'infinite',
+ }),
) as any
},
setQueryDefaults(options_, filters) {
return options.queryClient.setQueryDefaults(
- filters?.queryKey ??
- getQueryKeyFromPath(options.path, {
- input: filters?.input,
- type: 'query',
- }),
+ filters?.queryKey
+ ?? getQueryKeyFromPath(options.path, {
+ input: filters?.input,
+ type: 'query',
+ }),
options_ as any,
)
},
setInfiniteQueryDefaults(options_, filters) {
return options.queryClient.setQueryDefaults(
- filters?.queryKey ??
- getQueryKeyFromPath(options.path, {
- input: filters?.input,
- type: 'infinite',
- }),
+ filters?.queryKey
+ ?? getQueryKeyFromPath(options.path, {
+ input: filters?.input,
+ type: 'infinite',
+ }),
options_ as any,
)
},
diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts
index 1c9f6a16..dfa5d58e 100644
--- a/packages/react/src/index.ts
+++ b/packages/react/src/index.ts
@@ -2,7 +2,7 @@ export * from './general-hooks'
export * from './general-utils'
export * from './procedure-hooks'
export * from './procedure-utils'
+export * from './react'
export * from './react-context'
export * from './react-hooks'
export * from './react-utils'
-export * from './react'
diff --git a/packages/react/src/orpc-path.ts b/packages/react/src/orpc-path.ts
index b7b69101..2f554d18 100644
--- a/packages/react/src/orpc-path.ts
+++ b/packages/react/src/orpc-path.ts
@@ -15,7 +15,7 @@ export function getORPCPath(
const val = Reflect.get(orpc, orpcPathSymbol)
if (!Array.isArray(val)) {
- throw new Error(
+ throw new TypeError(
'orpcPathSymbol is not implemented, please use getORPCPath with correct instance.',
)
}
diff --git a/packages/react/src/procedure-hooks.test-d.ts b/packages/react/src/procedure-hooks.test-d.ts
index c346e8fb..1f86c47f 100644
--- a/packages/react/src/procedure-hooks.test-d.ts
+++ b/packages/react/src/procedure-hooks.test-d.ts
@@ -81,9 +81,9 @@ describe('useInfiniteQuery', () => {
expectTypeOf(query.data).toEqualTypeOf<
| undefined
| InfiniteData<
- SchemaOutput,
+ SchemaOutput,
number | undefined
- >
+ >
>()
})
@@ -111,11 +111,11 @@ describe('useInfiniteQuery', () => {
expectTypeOf(query.data).toEqualTypeOf<
| undefined
| {
- select: InfiniteData<
- SchemaOutput,
+ select: InfiniteData<
+ SchemaOutput,
number | undefined
- >
- }
+ >
+ }
>()
})
})
diff --git a/packages/react/src/procedure-hooks.test.tsx b/packages/react/src/procedure-hooks.test.tsx
index cbadcc29..f3a8b346 100644
--- a/packages/react/src/procedure-hooks.test.tsx
+++ b/packages/react/src/procedure-hooks.test.tsx
@@ -2,12 +2,12 @@ import type { SchemaOutput } from '@orpc/contract'
import { renderHook, screen, waitFor } from '@testing-library/react'
import {
ORPCContext,
+ queryClient,
type UserCreateInputSchema,
type UserFindInputSchema,
type UserListInputSchema,
type UserListOutputSchema,
type UserSchema,
- queryClient,
wrapper,
} from '../tests/orpc'
import { createProcedureHooks } from './procedure-hooks'
diff --git a/packages/react/src/procedure-hooks.ts b/packages/react/src/procedure-hooks.ts
index 22cb8ea7..c16e31ab 100644
--- a/packages/react/src/procedure-hooks.ts
+++ b/packages/react/src/procedure-hooks.ts
@@ -1,8 +1,9 @@
import type { Schema, SchemaInput, SchemaOutput } from '@orpc/contract'
+import type { SchemaInputForInfiniteQuery } from './types'
import {
+ get,
type PartialOnUndefinedDeep,
type SetOptional,
- get,
} from '@orpc/shared'
import {
type DefaultError,
@@ -10,35 +11,34 @@ import {
type FetchQueryOptions,
type InfiniteData,
type QueryKey,
+ useInfiniteQuery,
type UseInfiniteQueryOptions,
type UseInfiniteQueryResult,
+ useMutation,
type UseMutationOptions,
type UseMutationResult,
+ usePrefetchInfiniteQuery,
+ usePrefetchQuery,
+ useQuery,
type UseQueryOptions,
type UseQueryResult,
+ useSuspenseInfiniteQuery,
type UseSuspenseInfiniteQueryOptions,
type UseSuspenseInfiniteQueryResult,
+ useSuspenseQuery,
type UseSuspenseQueryOptions,
type UseSuspenseQueryResult,
- useInfiniteQuery,
- useMutation,
- usePrefetchInfiniteQuery,
- usePrefetchQuery,
- useQuery,
- useSuspenseInfiniteQuery,
- useSuspenseQuery,
} from '@tanstack/react-query'
import { orpcPathSymbol } from './orpc-path'
import { type ORPCContext, useORPCContext } from './react-context'
import { getMutationKeyFromPath, getQueryKeyFromPath } from './tanstack-key'
-import type { SchemaInputForInfiniteQuery } from './types'
export interface ProcedureHooks<
TInputSchema extends Schema,
TOutputSchema extends Schema,
THandlerOutput extends SchemaOutput,
> {
- useQuery>(
+ useQuery: >(
input: SchemaInput,
options?: SetOptional<
UseQueryOptions<
@@ -48,8 +48,8 @@ export interface ProcedureHooks<
>,
'queryFn' | 'queryKey'
>,
- ): UseQueryResult
- useInfiniteQuery<
+ ) => UseQueryResult
+ useInfiniteQuery: <
USelectData = InfiniteData<
SchemaOutput,
SchemaInput['cursor']
@@ -70,9 +70,9 @@ export interface ProcedureHooks<
input: SchemaInputForInfiniteQuery
}
>,
- ): UseInfiniteQueryResult
+ ) => UseInfiniteQueryResult
- useSuspenseQuery>(
+ useSuspenseQuery: >(
input: SchemaInput,
options?: SetOptional<
UseSuspenseQueryOptions<
@@ -82,8 +82,8 @@ export interface ProcedureHooks<
>,
'queryFn' | 'queryKey'
>,
- ): UseSuspenseQueryResult
- useSuspenseInfiniteQuery<
+ ) => UseSuspenseQueryResult
+ useSuspenseInfiniteQuery: <
USelectData = InfiniteData<
SchemaOutput,
SchemaInput['cursor']
@@ -104,13 +104,13 @@ export interface ProcedureHooks<
input: SchemaInputForInfiniteQuery
}
>,
- ): UseSuspenseInfiniteQueryResult
+ ) => UseSuspenseInfiniteQueryResult
- usePrefetchQuery(
+ usePrefetchQuery: (
input: SchemaInput,
options?: FetchQueryOptions>,
- ): void
- usePrefetchInfiniteQuery(
+ ) => void
+ usePrefetchInfiniteQuery: (
options: PartialOnUndefinedDeep<
SetOptional<
FetchInfiniteQueryOptions<
@@ -125,9 +125,9 @@ export interface ProcedureHooks<
input: SchemaInputForInfiniteQuery
}
>,
- ): void
+ ) => void
- useMutation(
+ useMutation: (
options?: SetOptional<
UseMutationOptions<
SchemaOutput,
@@ -136,7 +136,7 @@ export interface ProcedureHooks<
>,
'mutationFn' | 'mutationKey'
>,
- ): UseMutationResult<
+ ) => UseMutationResult<
SchemaOutput,
DefaultError,
SchemaInput
@@ -158,7 +158,7 @@ export function createProcedureHooks<
TInputSchema extends Schema = undefined,
TOutputSchema extends Schema = undefined,
THandlerOutput extends
- SchemaOutput = SchemaOutput,
+ SchemaOutput = SchemaOutput,
>(
options: CreateProcedureHooksOptions,
): ProcedureHooks {
@@ -261,7 +261,7 @@ export function createProcedureHooks<
return useMutation(
{
mutationKey: getMutationKeyFromPath(options.path),
- mutationFn: (input) => client(input),
+ mutationFn: input => client(input),
...options_,
},
context.queryClient,
diff --git a/packages/react/src/procedure-utils.test-d.ts b/packages/react/src/procedure-utils.test-d.ts
index 2cba25c3..ce43233a 100644
--- a/packages/react/src/procedure-utils.test-d.ts
+++ b/packages/react/src/procedure-utils.test-d.ts
@@ -233,9 +233,9 @@ describe('getInfiniteQueryData', () => {
expectTypeOf(data).toEqualTypeOf<
| undefined
| InfiniteData<
- SchemaOutput,
+ SchemaOutput,
number | undefined
- >
+ >
>()
})
})
@@ -377,11 +377,11 @@ describe('getInfiniteQueryState', () => {
expectTypeOf(data).toEqualTypeOf<
| undefined
| QueryState<
- InfiniteData<
- SchemaOutput,
+ InfiniteData<
+ SchemaOutput,
number | undefined
- >
>
+ >
>()
})
})
@@ -444,9 +444,9 @@ describe('setInfiniteQueryData', () => {
expectTypeOf(data).toEqualTypeOf<
| undefined
| InfiniteData<
- SchemaOutput,
+ SchemaOutput,
number | undefined
- >
+ >
>()
return {
@@ -458,9 +458,9 @@ describe('setInfiniteQueryData', () => {
expectTypeOf(data).toEqualTypeOf<
| undefined
| InfiniteData<
- SchemaOutput,
+ SchemaOutput,
number | undefined
- >
+ >
>()
})
diff --git a/packages/react/src/procedure-utils.test.tsx b/packages/react/src/procedure-utils.test.tsx
index adff071d..7ce06a4f 100644
--- a/packages/react/src/procedure-utils.test.tsx
+++ b/packages/react/src/procedure-utils.test.tsx
@@ -9,7 +9,7 @@ describe('fetchQuery', () => {
const utils = createProcedureUtils({
client: orpcClient.user.find,
path: ['user', 'find'],
- queryClient: queryClient,
+ queryClient,
})
it('on success', async () => {
@@ -40,7 +40,7 @@ describe('fetchInfiniteQuery', () => {
const utils = createProcedureUtils({
client: orpcClient.user.list,
path: ['user', 'list'],
- queryClient: queryClient,
+ queryClient,
})
it('on success', async () => {
@@ -76,7 +76,7 @@ describe('prefetchQuery', () => {
const utils = createProcedureUtils({
client: orpcClient.user.find,
path: ['user', 'find'],
- queryClient: queryClient,
+ queryClient,
})
it('on success', async () => {
@@ -109,7 +109,7 @@ describe('prefetchInfiniteQuery', () => {
const utils = createProcedureUtils({
client: orpcClient.user.list,
path: ['user', 'list'],
- queryClient: queryClient,
+ queryClient,
})
it('on success', async () => {
@@ -144,7 +144,7 @@ describe('ensureQueryData', () => {
const utils = createProcedureUtils({
client: orpcClient.user.find,
path: ['user', 'find'],
- queryClient: queryClient,
+ queryClient,
})
it('on success', async () => {
@@ -175,7 +175,7 @@ describe('ensureInfiniteQuery', () => {
const utils = createProcedureUtils({
client: orpcClient.user.list,
path: ['user', 'list'],
- queryClient: queryClient,
+ queryClient,
})
it('on success', async () => {
@@ -211,7 +211,7 @@ describe('getQueryData', () => {
const utils = createProcedureUtils({
client: orpcClient.user.find,
path: ['user', 'find'],
- queryClient: queryClient,
+ queryClient,
})
it('on success', async () => {
@@ -225,7 +225,7 @@ describe('getInfiniteQueryData', () => {
const utils = createProcedureUtils({
client: orpcClient.user.list,
path: ['user', 'list'],
- queryClient: queryClient,
+ queryClient,
})
it('on success', async () => {
@@ -239,7 +239,7 @@ describe('getQueryState', () => {
const utils = createProcedureUtils({
client: orpcClient.user.find,
path: ['user', 'find'],
- queryClient: queryClient,
+ queryClient,
})
it('on success', async () => {
@@ -256,7 +256,7 @@ describe('getInfiniteQueryState', () => {
const utils = createProcedureUtils({
client: orpcClient.user.list,
path: ['user', 'list'],
- queryClient: queryClient,
+ queryClient,
})
it('on success', async () => {
@@ -273,7 +273,7 @@ describe('setQueryData', () => {
const utils = createProcedureUtils({
client: orpcClient.user.find,
path: ['user', 'find'],
- queryClient: queryClient,
+ queryClient,
})
it('on success', async () => {
@@ -299,11 +299,11 @@ describe('setQueryData', () => {
})
})
-describe('getInfiniteQueryData', () => {
+describe('getInfiniteQueryData 2', () => {
const utils = createProcedureUtils({
client: orpcClient.user.list,
path: ['user', 'list'],
- queryClient: queryClient,
+ queryClient,
})
it('on success', async () => {
diff --git a/packages/react/src/procedure-utils.ts b/packages/react/src/procedure-utils.ts
index da7493c3..25ca704d 100644
--- a/packages/react/src/procedure-utils.ts
+++ b/packages/react/src/procedure-utils.ts
@@ -14,22 +14,22 @@ import type {
SetDataOptions,
Updater,
} from '@tanstack/react-query'
-import { getQueryKeyFromPath } from './tanstack-key'
import type { SchemaInputForInfiniteQuery } from './types'
+import { getQueryKeyFromPath } from './tanstack-key'
export interface ProcedureUtils<
TInputSchema extends Schema,
TOutputSchema extends Schema,
THandlerOutput extends SchemaOutput,
> {
- fetchQuery(
+ fetchQuery: (
input: SchemaInput,
options?: SetOptional<
FetchQueryOptions>,
'queryKey' | 'queryFn'
>,
- ): Promise>
- fetchInfiniteQuery(
+ ) => Promise>
+ fetchInfiniteQuery: (
options: PartialOnUndefinedDeep<
SetOptional<
FetchInfiniteQueryOptions<
@@ -44,21 +44,21 @@ export interface ProcedureUtils<
input: SchemaInputForInfiniteQuery
}
>,
- ): Promise<
+ ) => Promise<
InfiniteData<
SchemaOutput,
SchemaInput['cursor']
>
>
- prefetchQuery(
+ prefetchQuery: (
input: SchemaInput,
options?: SetOptional<
FetchQueryOptions>,
'queryKey' | 'queryFn'
>,
- ): Promise
- prefetchInfiniteQuery(
+ ) => Promise
+ prefetchInfiniteQuery: (
options: PartialOnUndefinedDeep<
SetOptional<
FetchInfiniteQueryOptions<
@@ -73,28 +73,27 @@ export interface ProcedureUtils<
input: SchemaInputForInfiniteQuery
}
>,
- ): Promise
+ ) => Promise
- getQueryData(
+ getQueryData: (
input: SchemaInput,
- ): SchemaOutput | undefined
- getInfiniteQueryData(
+ ) => SchemaOutput | undefined
+ getInfiniteQueryData: (
input: SchemaInputForInfiniteQuery,
- ):
- | InfiniteData<
- SchemaOutput,
- SchemaInput['cursor']
- >
- | undefined
+ ) => | InfiniteData<
+ SchemaOutput,
+ SchemaInput['cursor']
+ >
+ | undefined
- ensureQueryData(
+ ensureQueryData: (
input: SchemaInput,
options?: SetOptional<
EnsureQueryDataOptions>,
'queryFn' | 'queryKey'
>,
- ): Promise>
- ensureInfiniteQueryData(
+ ) => Promise>
+ ensureInfiniteQueryData: (
options: PartialOnUndefinedDeep<
SetOptional<
EnsureInfiniteQueryDataOptions<
@@ -109,63 +108,61 @@ export interface ProcedureUtils<
input: SchemaInputForInfiniteQuery
}
>,
- ): Promise<
+ ) => Promise<
InfiniteData<
SchemaOutput,
SchemaInput['cursor']
>
>
- getQueryState(
+ getQueryState: (
input: SchemaInput,
- ): QueryState> | undefined
- getInfiniteQueryState(
+ ) => QueryState> | undefined
+ getInfiniteQueryState: (
input: SchemaInputForInfiniteQuery,
- ):
- | QueryState<
- InfiniteData<
- SchemaOutput,
- SchemaInput['cursor']
- >
- >
- | undefined
+ ) => | QueryState<
+ InfiniteData<
+ SchemaOutput,
+ SchemaInput['cursor']
+ >
+ >
+ | undefined
- setQueryData(
+ setQueryData: (
input: SchemaInput,
updater: Updater<
SchemaOutput | undefined,
SchemaOutput | undefined
>,
options?: SetDataOptions,
- ): SchemaOutput | undefined
- setInfiniteQueryData(
+ ) => SchemaOutput | undefined
+ setInfiniteQueryData: (
input: SchemaInputForInfiniteQuery,
updater: Updater<
| InfiniteData<
- SchemaOutput,
- SchemaInput['cursor']
- >
+ SchemaOutput,
+ SchemaInput['cursor']
+ >
| undefined,
| InfiniteData<
- SchemaOutput,
- SchemaInput['cursor']
- >
- | undefined
- >,
- options?: SetDataOptions,
- ):
- | InfiniteData<
SchemaOutput,
SchemaInput['cursor']
>
- | undefined
+ | undefined
+ >,
+ options?: SetDataOptions,
+ ) => | InfiniteData<
+ SchemaOutput,
+ SchemaInput['cursor']
+ >
+ | undefined
}
export interface CreateProcedureUtilsOptions<
TInputSchema extends Schema = undefined,
TOutputSchema extends Schema = undefined,
THandlerOutput extends
- SchemaOutput = SchemaOutput,
+ SchemaOutput = SchemaOutput,
> {
client: ProcedureClient
queryClient: QueryClient
diff --git a/packages/react/src/react-hooks.ts b/packages/react/src/react-hooks.ts
index dd7d7d25..a0ec2d60 100644
--- a/packages/react/src/react-hooks.ts
+++ b/packages/react/src/react-hooks.ts
@@ -4,33 +4,25 @@ import type {
SchemaOutput,
} from '@orpc/contract'
import type { Procedure, Router } from '@orpc/server'
-import { type GeneralHooks, createGeneralHooks } from './general-hooks'
-import { orpcPathSymbol } from './orpc-path'
-import { type ProcedureHooks, createProcedureHooks } from './procedure-hooks'
import type { ORPCContext } from './react-context'
+import { createGeneralHooks, type GeneralHooks } from './general-hooks'
+import { orpcPathSymbol } from './orpc-path'
+import { createProcedureHooks, type ProcedureHooks } from './procedure-hooks'
export type ORPCHooksWithContractRouter = {
[K in keyof TRouter]: TRouter[K] extends ContractProcedure<
infer UInputSchema,
infer UOutputSchema
>
- ? ProcedureHooks> &
- GeneralHooks>
+ ? ProcedureHooks> & GeneralHooks>
: TRouter[K] extends ContractRouter
? ORPCHooksWithContractRouter
: never
} & GeneralHooks
export type ORPCHooksWithRouter> = {
- [K in keyof TRouter]: TRouter[K] extends Procedure<
- any,
- any,
- infer UInputSchema,
- infer UOutputSchema,
- infer UHandlerOutput
- >
- ? ProcedureHooks &
- GeneralHooks
+ [K in keyof TRouter]: TRouter[K] extends Procedure
+ ? ProcedureHooks & GeneralHooks
: TRouter[K] extends Router
? ORPCHooksWithRouter
: never
@@ -52,19 +44,19 @@ export interface CreateORPCHooksOptions<
export function createORPCHooks>(
options: CreateORPCHooksOptions,
): TRouter extends Router
- ? ORPCHooksWithRouter
- : TRouter extends ContractRouter
- ? ORPCHooksWithContractRouter
- : never {
+ ? ORPCHooksWithRouter
+ : TRouter extends ContractRouter
+ ? ORPCHooksWithContractRouter
+ : never {
const path = options.path ?? []
const generalHooks = createGeneralHooks({ context: options.context, path })
// for sure root is not procedure, so do not it procedure hooks on root
const procedureHooks = path.length
? createProcedureHooks({
- context: options.context,
- path,
- })
+ context: options.context,
+ path,
+ })
: {}
return new Proxy(
diff --git a/packages/react/src/react-utils.ts b/packages/react/src/react-utils.ts
index 8c630ef9..008ccc1e 100644
--- a/packages/react/src/react-utils.ts
+++ b/packages/react/src/react-utils.ts
@@ -5,32 +5,21 @@ import type {
SchemaOutput,
} from '@orpc/contract'
import type { Procedure, Router } from '@orpc/server'
-import { type GeneralUtils, createGeneralUtils } from './general-utils'
-import { type ProcedureUtils, createProcedureUtils } from './procedure-utils'
import type { ORPCContextValue } from './react-context'
+import { createGeneralUtils, type GeneralUtils } from './general-utils'
+import { createProcedureUtils, type ProcedureUtils } from './procedure-utils'
export type ORPCUtilsWithContractRouter = {
- [K in keyof TRouter]: TRouter[K] extends ContractProcedure<
- infer UInputSchema,
- infer UOutputSchema
- >
- ? ProcedureUtils> &
- GeneralUtils>
+ [K in keyof TRouter]: TRouter[K] extends ContractProcedure
+ ? ProcedureUtils> & GeneralUtils>
: TRouter[K] extends ContractRouter
? ORPCUtilsWithContractRouter
: never
} & GeneralUtils
export type ORPCUtilsWithRouter> = {
- [K in keyof TRouter]: TRouter[K] extends Procedure<
- any,
- any,
- infer UInputSchema,
- infer UOutputSchema,
- infer UHandlerOutput
- >
- ? ProcedureUtils &
- GeneralUtils
+ [K in keyof TRouter]: TRouter[K] extends Procedure
+ ? ProcedureUtils & GeneralUtils
: TRouter[K] extends Router
? ORPCUtilsWithRouter
: never
@@ -52,10 +41,10 @@ export interface CreateORPCUtilsOptions<
export function createORPCUtils>(
options: CreateORPCUtilsOptions,
): TRouter extends Router
- ? ORPCUtilsWithRouter
- : TRouter extends ContractRouter
- ? ORPCUtilsWithContractRouter
- : never {
+ ? ORPCUtilsWithRouter
+ : TRouter extends ContractRouter
+ ? ORPCUtilsWithContractRouter
+ : never {
const path = options.path ?? []
const client = options.contextValue.client as any
@@ -67,10 +56,10 @@ export function createORPCUtils>(
// for sure root is not procedure, so do not it procedure utils on root
const procedureUtils = path.length
? createProcedureUtils({
- client,
- queryClient: options.contextValue.queryClient,
- path,
- })
+ client,
+ queryClient: options.contextValue.queryClient,
+ path,
+ })
: {}
return new Proxy(
diff --git a/packages/react/src/react.test-d.ts b/packages/react/src/react.test-d.ts
index ec78f192..efbc95d5 100644
--- a/packages/react/src/react.test-d.ts
+++ b/packages/react/src/react.test-d.ts
@@ -1,16 +1,16 @@
import type { SchemaOutput } from '@orpc/contract'
import type { QueryClient } from '@tanstack/react-query'
+import type { GeneralHooks } from './general-hooks'
+import type { GeneralUtils } from './general-utils'
+import type { ProcedureHooks } from './procedure-hooks'
+import type { ProcedureUtils } from './procedure-utils'
import {
+ orpc,
+ orpcClient,
ORPCContext,
type UserFindInputSchema,
type UserSchema,
- orpc,
- orpcClient,
} from '../tests/orpc'
-import type { GeneralHooks } from './general-hooks'
-import type { GeneralUtils } from './general-utils'
-import type { ProcedureHooks } from './procedure-hooks'
-import type { ProcedureUtils } from './procedure-utils'
import { useQueriesFactory } from './use-queries/hook'
describe('useUtils', () => {
diff --git a/packages/react/src/react.test.tsx b/packages/react/src/react.test.tsx
index 99999abe..7fcc04c2 100644
--- a/packages/react/src/react.test.tsx
+++ b/packages/react/src/react.test.tsx
@@ -6,7 +6,7 @@ beforeEach(() => {
})
it('useUtils', async () => {
- const { result } = renderHook(() => orpc.useUtils(), { wrapper: wrapper })
+ const { result } = renderHook(() => orpc.useUtils(), { wrapper })
const promise = result.current.user.find.ensureQueryData({ id: '1' })
expect(result.current.user.isFetching()).toBe(1)
@@ -26,7 +26,7 @@ it('useUtils', async () => {
})
it('useContext', async () => {
- const { result } = renderHook(() => orpc.useContext(), { wrapper: wrapper })
+ const { result } = renderHook(() => orpc.useContext(), { wrapper })
expect(result.current.client).toBe(orpcClient)
expect(result.current.queryClient).toBe(queryClient)
@@ -38,8 +38,8 @@ it('useContext', async () => {
it('useQueries', async () => {
const queries = renderHook(
- () => orpc.useQueries((o) => [o.user.find({ id: '123' })]),
- { wrapper: wrapper },
+ () => orpc.useQueries(o => [o.user.find({ id: '123' })]),
+ { wrapper },
)
await waitFor(() =>
@@ -52,20 +52,20 @@ it('useQueries', async () => {
it('hooks', async () => {
const isFetching = renderHook(() => orpc.user.useIsFetching(), {
- wrapper: wrapper,
+ wrapper,
})
const isMutating = renderHook(() => orpc.user.useIsMutating(), {
- wrapper: wrapper,
+ wrapper,
})
expect(isFetching.result.current).toBe(0)
expect(isMutating.result.current).toBe(0)
const query = renderHook(() => orpc.user.find.useQuery({ id: '1' }), {
- wrapper: wrapper,
+ wrapper,
})
const mutation = renderHook(() => orpc.user.create.useMutation(), {
- wrapper: wrapper,
+ wrapper,
})
await waitFor(() => expect(query.result.current.status).toEqual('pending'))
diff --git a/packages/react/src/react.tsx b/packages/react/src/react.tsx
index ae4df093..b865de4f 100644
--- a/packages/react/src/react.tsx
+++ b/packages/react/src/react.tsx
@@ -1,25 +1,25 @@
import type { ContractRouter } from '@orpc/contract'
import type { Router } from '@orpc/server'
import {
+ createORPCContext,
type ORPCContext,
type ORPCContextValue,
- createORPCContext,
useORPCContext,
} from './react-context'
import {
+ createORPCHooks,
type ORPCHooksWithContractRouter,
type ORPCHooksWithRouter,
- createORPCHooks,
} from './react-hooks'
import {
+ createORPCUtils,
type ORPCUtilsWithContractRouter,
type ORPCUtilsWithRouter,
- createORPCUtils,
} from './react-utils'
import {
+ useQueriesFactory,
type UseQueriesWithContractRouter,
type UseQueriesWithRouter,
- useQueriesFactory,
} from './use-queries/hook'
export type ORPCReactWithContractRouter =
@@ -49,6 +49,7 @@ export function createORPCReact<
const Context = createORPCContext()
const useContext = () => useORPCContext(Context)
const useUtils = () => createORPCUtils({ contextValue: useContext() })
+ // eslint-disable-next-line react-hooks/rules-of-hooks
const useQueries = useQueriesFactory({ context: Context })
const hooks = createORPCHooks({ context: Context })
diff --git a/packages/react/src/tanstack-key.ts b/packages/react/src/tanstack-key.ts
index bf42a2c0..723b49d8 100644
--- a/packages/react/src/tanstack-key.ts
+++ b/packages/react/src/tanstack-key.ts
@@ -1,12 +1,12 @@
import type { SchemaInput } from '@orpc/contract'
import type { PartialDeep } from '@orpc/shared'
import type { MutationKey, QueryKey } from '@tanstack/react-query'
-import { getORPCPath } from './orpc-path'
import type { ProcedureHooks } from './procedure-hooks'
import type {
ORPCHooksWithContractRouter,
ORPCHooksWithRouter,
} from './react-hooks'
+import { getORPCPath } from './orpc-path'
export type QueryType = 'query' | 'infinite' | undefined
@@ -17,9 +17,9 @@ export interface GetQueryKeyOptions