Skip to content

Commit

Permalink
fix: minor block statements fixse
Browse files Browse the repository at this point in the history
  • Loading branch information
OrJDev committed Nov 5, 2024
1 parent 20f4bd2 commit 3303013
Show file tree
Hide file tree
Showing 11 changed files with 139 additions and 89 deletions.
6 changes: 6 additions & 0 deletions .changeset/violet-carrots-reflect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@solid-mediakit/prpc-plugin': patch
'@solid-mediakit/prpc': patch
---

fix: minor block statements fixse
13 changes: 0 additions & 13 deletions docs/src/content/docs/authpc/createcaller.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -155,19 +155,6 @@ export const getRequest2 = createCaller(() => {
)
})

// this will not be wrapped with solid's `cache`
export const notCached = createCaller(
() => {
return response$(
{ iSetTheHeader: true },
{ headers: { 'cache-control': 'max-age=60' } },
)
},
{
cached: false,
},
)

export const protectedQuery = createCaller(
({ session$ }) => {
console.log(session$.user)
Expand Down
13 changes: 0 additions & 13 deletions docs/src/content/docs/prpc/createcaller.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -155,19 +155,6 @@ export const getRequest2 = createCaller(() => {
)
})

// this will not be wrapped with solid's `cache`
export const notCached = createCaller(
() => {
return response$(
{ iSetTheHeader: true },
{ headers: { 'cache-control': 'max-age=60' } },
)
},
{
cached: false,
},
)

export const protectedQuery = createCaller(
({ session$ }) => {
console.log(session$.user)
Expand Down
2 changes: 1 addition & 1 deletion examples/prpc/src/routes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const Home: VoidComponent = () => {
<button
onClick={() => {
try {
myMutation.mutateAsync({ ok: 3, test: { l: 'test' } })
myMutation.mutateAsync({ ok: 4, test: { l: 'test' } })
} catch (e) {
console.error('here', e)
}
Expand Down
3 changes: 3 additions & 0 deletions examples/prpc/src/use/test2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { createCaller, redirect$ } from '@solid-mediakit/prpc'

export const redirectRequet = createCaller(() => redirect$('/test'))
8 changes: 7 additions & 1 deletion examples/prpc/src/use/use.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { z } from 'zod'
import { createCaller, error$, response$ } from '@solid-mediakit/prpc'
import {
createCaller,
error$,
redirect$,
response$,
} from '@solid-mediakit/prpc'

export const withMws = createCaller
.use(async () => {
Expand Down Expand Up @@ -56,6 +61,7 @@ export const getRequest = createCaller(
export const mutationTest3 = qfn(
z.object({ ok: z.number(), test: z.object({ l: z.string() }) }),
({ input$ }) => {
if (input$.ok === 4) return redirect$('/test')
return `${input$.ok}`
},
{
Expand Down
12 changes: 9 additions & 3 deletions packages/prpc/plugin/src/compiler/babel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,15 @@ export function createTransform$(opts?: PRPCPluginOptions<any>) {
true,
)

;(originFn.body as any).body.unshift(
t.expressionStatement(t.stringLiteral('use server')),
)
const expr = t.expressionStatement(t.stringLiteral('use server'))
if (Array.isArray((originFn.body as any)?.body)) {
;(originFn.body as any).body.unshift(expr)
} else {
;(originFn.body as any) = t.blockStatement([
expr,
t.returnStatement(originFn.body as any),
])
}

if (args._method === 'GET') {
importIfNotThere(
Expand Down
13 changes: 0 additions & 13 deletions packages/prpc/solid/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,19 +208,6 @@ export const getRequest2 = createCaller(() => {
{ headers: { 'cache-control': 'max-age=60' } },
)
})

// this will not be wrapped with solid's `cache`
export const notCached = createCaller(
() => {
return response$(
{ iSetTheHeader: true },
{ headers: { 'cache-control': 'max-age=60' } },
)
},
{
cached: false,
},
)
```

#### POST
Expand Down
52 changes: 38 additions & 14 deletions packages/prpc/solid/src/createCaller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@ import type {
QueryRes,
} from './types'
import type { ZodSchema, infer as _ZodInfer } from 'zod'
import { wrapFn } from './wrap'
import { isRedirectResponse, wrapFn } from './wrap'
import {
createMutation,
createQuery,
useQueryClient,
} from '@tanstack/solid-query'
import { mergeProps } from 'solid-js/web'

export const createCaller = new Proxy(
(...args: any[]) => {
Expand Down Expand Up @@ -68,34 +69,41 @@ function _ACTION$(...args: any[]): QueryRes<any, any> {
if (actualOpts?.type === 'action') {
return new Proxy(
(opts?: Action$Options<any, any, any>) => {
return createMutation(() => ({
mutationFn: async (input) =>
await wrapFn(fn, input, actualOpts.method ?? 'POST'),
mutationKey: ['prpc', 'mutation', key],
...((opts?.() ?? {}) as any),
}))
const newOpts = getNewMutationOpts(opts)
return createMutation(() => {
return {
mutationFn: async (input) =>
await wrapFn(fn, input, actualOpts.method ?? 'POST'),
mutationKey: ['prpc', 'mutation', key],
...((newOpts?.() ?? {}) as any),
}
})
},
{
get(target, prop) {
if (prop === 'raw') {
return async (input: any) =>
await wrapFn(fn, input, actualOpts.method ?? 'POST')
}

return (target as any)[prop]
},
},
) as any
}

const useUtils = createUseUtils(key)
return new Proxy(
(input: any, opts?: GET$Options<undefined, any>) => {
return createQuery(() => ({
queryFn: async () =>
await wrapFn(fn, input, actualOpts.method ?? 'POST'),
queryKey: ['prpc', 'query', key, input ? input() : undefined],
experimental_prefetchInRender: true,
...((opts?.() ?? {}) as any),
}))
return createQuery(() => {
return {
queryFn: async () =>
await wrapFn(fn, input, actualOpts.method ?? 'POST'),
queryKey: ['prpc', 'query', key, input ? input() : undefined],
experimental_prefetchInRender: true,
...((opts?.() ?? {}) as any),
}
})
},
{
get(target, prop) {
Expand Down Expand Up @@ -151,3 +159,19 @@ export const createUseUtils = (key: string) => {
}
return useUtils
}

const getNewMutationOpts = (queryOpts?: () => any) => {
const navigate = (url?: string | null) => void url
return () =>
mergeProps(queryOpts?.(), {
onSuccess: async (data: Response, variables: any, context: any) => {
if (data instanceof Response) {
if (isRedirectResponse(data)) {
navigate(data.headers.get('Location'))
}
} else {
return queryOpts?.().onSuccess?.(data, variables, context)
}
},
})
}
8 changes: 7 additions & 1 deletion packages/prpc/solid/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,13 @@ export const validateSchema = async <Schema extends RequiredAllowedSchemas>(
}

export const redirect$ = (url: string, init?: ResponseInit) => {
return redirect(url, init)
return redirect(url, {
...init,
headers: {
...init?.headers,
'X-pRPC-Redirect': '1',
},
})
}

export const response$ = <T>(data: T, init?: ResponseInit): T => {
Expand Down
98 changes: 68 additions & 30 deletions packages/prpc/solid/src/wrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,38 +6,58 @@ export async function wrapFn<Fn extends ExpectedFn$<any, any>>(
callFn: Fn,
input: any,
method: 'GET' | 'POST',
handleResponse = genHandleResponse(),
) {
const input$ = input
? typeof input === 'function'
? input()
: input
: undefined
try {
const response = await callFn(
method === 'GET' ? (JSON.stringify(input$) as any) : { input$ },
)
if (response instanceof Response) {
handleResponse?.(response)
const url = response.headers.get('location')
if (response.headers.get('X-pRPC-Error') === '1') {
const isValidationError =
response.headers.get('X-pRPC-Validation') === '1'
const error = await optionalData(response)
throw new PRPClientError(
error.error.message,
isValidationError ? error.error.issues : error.error,
isValidationError,
)
} else if (!isRedirectResponse(response) || !url) {
return await optionalData(response)
const innerFn = async () => {
const handleResponse = genHandleResponse()

const input$ = input
? typeof input === 'function'
? input()
: input
: undefined
try {
const response = await callFn(
method === 'GET' ? (JSON.stringify(input$) as any) : { input$ },
)
if (response instanceof Response) {
const url = response.headers.get('Location')
const isRedirect = isRedirectResponse(response) ? url : null
handleResponse?.(response, isRedirect)
if (response.headers.get('X-pRPC-Error') === '1') {
const isValidationError =
response.headers.get('X-pRPC-Validation') === '1'
const error = await optionalData(response)
throw new PRPClientError(
error.error.message,
isValidationError ? error.error.issues : error.error,
isValidationError,
)
} else if (isRedirect) {
return {
['prpc-redirect']: isRedirect,
}
}

// else if (isRedirect) {
// if (url !== null) {
// if (navigate && url.startsWith('/'))
// startTransition(() => {
// navigate(url, { replace: true })
// })
// else if (!isServer) window.Location.href = url
// }
// } else {
// return await optionalData(response)
// }
else return await optionalData(response)
}
return response
} catch (e: any) {
if (e instanceof PRPClientError) throw e
throw new PRPClientError(e.message, e)
}
return response
} catch (e: any) {
if (e instanceof PRPClientError) throw e
throw new PRPClientError(e.message, e)
}
return await innerFn()
}

export const optionalData = async (response: Response) => {
Expand All @@ -54,20 +74,38 @@ export function isRedirectResponse(response: Response): response is Response {
return (
response &&
response instanceof Response &&
redirectStatusCodes.has(response.status)
(redirectStatusCodes.has(response.status) ||
response.headers.get('X-pRPC-Redirect') === '1')
)
}

export const genHandleResponse = () => {
const event = getRequestEvent()
return (response: Response) => {
return (response: Response, isRedirect: string | null) => {
if (isServer && event) {
if ((event as any).response) {
response.headers.forEach((value, key) => {
if (key === 'content-type') return
;(event as any).response.headers.set(key, value)
})
}
if (isRedirect) {
event.response.headers.set('Location', isRedirect)
event.response.status = 302
}
}
}
}

export function handleRedirect(response: Response, useRouter?: boolean) {
const url = response.headers.get('Location')
if (url) {
if (typeof window !== 'undefined' && !useRouter) {
window.location.href = url
} else {
return {
redirect: url,
}
}
}
}

0 comments on commit 3303013

Please sign in to comment.