Skip to content

ViktorQvarfordt/refimpl-typed-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

refimpl-typed-api

A reference implementation of a fully typed API layer shared between a React client and an Express server, using Zod for runtime validation.

Idea

  • shared/api.ts has endpoint = { path: string, input: ZodType, output: ZodType } definitions used by server and client. Input and output types are constrained to be JSON serializable at the type level.

  • server/api.ts has a route function to create typesafe routes based on endpoint objects. The register function is separate to retain control of when routes are declared which is important since express routes are built up in a stateful manner. We don't want side effects in any other file but server.ts. Use throw new ApiError(..) to handle errors and do authentication (401) and authorization (403).

  • client/api.ts has callApi and useApi functions that take an endpoint and does the correct fetching and type validation.

Example: Access control

const getAdminSettings = endpoint(
  '/api/get-admin-settings',
  z.null(),
  z.object({ someData: z.number() }),
)

export const getAdminSettingsRoute = route(getAdminSettings, async (input, req) => {
  if (!isAdmin(req)) throw new ApiError(403, 'Forbidden')
  return { someData: 7 }
})

Run locally

./dev

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors