Last active
October 29, 2022 02:16
-
-
Save reggi/e2094a2309a6104bab14ae0749d1e6e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useContext } from 'preact/hooks'; | |
import { createContext, Fragment, JSX } from 'preact'; | |
import { HandlerContext, Handlers, PageProps } from "$fresh/server.ts"; | |
const RequestContext = createContext(new Request('http://localhost:8000/')); | |
const useRequest = () => useContext(RequestContext); | |
export const passRequestHandler: Handlers<Request> = { | |
GET(request, ctx) { | |
return ctx.render(request); | |
}, | |
POST(request, ctx) { | |
return ctx.render(request); | |
}, | |
PUT(request, ctx) { | |
return ctx.render(request); | |
}, | |
DELETE(request, ctx) { | |
return ctx.render(request); | |
}, | |
}; | |
export function withRequest(Component: (props: any) => JSX.Element) { | |
return ({ data }: PageProps<Request>) => { | |
return ( | |
<RequestContext.Provider value={data}> | |
{<Component/>} | |
</RequestContext.Provider> | |
) | |
} | |
} | |
export function withData<T extends {[key: string]: any}>(Component: (props: T) => JSX.Element, useHook: (req: Request) => T) { | |
return ({ data }: PageProps<any>) => { | |
const req = data instanceof Request ? data : useRequest() | |
const props = useHook(req) | |
return ( | |
<Component {...props}/> | |
) | |
} | |
} | |
export function withDataRequest<T extends {[key: string]: any}>(Component: (props: T) => JSX.Element, useHook: (req: Request) => T) { | |
return withRequest(withData(Component, useHook)) | |
} | |
// this shifts the { data } prop from the route to be spread top-level | |
export function withShiftData <T>(Component: (props: T) => JSX.Element) { | |
return ({ data }: PageProps<any>) => { | |
return <Component {...data} /> | |
} | |
} | |
export function getRequest<T>(useHook: (req: Request, ctx?: HandlerContext<T, Record<string, unknown>>) => T) { | |
const handlers: Handlers<T> = { | |
GET(req, ctx) { | |
const res = useHook(req, ctx); | |
if (res instanceof Response) return res; | |
return ctx.render(res); | |
} | |
} | |
return handlers | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment