ecyrbe / zodios

typescript http client and server with zod validation
https://www.zodios.org/
MIT License
1.71k stars 46 forks source link

Function to create a single endpoint definition #149

Closed Todomir closed 2 years ago

Todomir commented 2 years ago

We currently have an file with a bunch of route definitions. The readability really starts to get worse as the file grow, having an makeEndpoint method would be specially useful when we want one definition per file, e.g:

// getUser.ts

export default makeEndpoint({
  method: "get",
  path: "/users/:id",
  alias: "getUser",
  description: "Get a user",
  response: z.object({
    id: z.number(),
    name: z.string(),
  }),
})
// createUser.ts

export default makeEndpoint({
  method: "post",
  path: "/users",
  alias: "createUser",
  description: "Create a user",
  parameters: [{
    name: 'body',
    type: 'Body',
    schema: z.object({
      name: z.string(),
    })
  }],
  response: z.object({
    id: z.number(),
    name: z.string(),
  }),
})
// api.ts
import getUser from './getUser';
import createUser from './createUser';

// It could also be compatible `makeApi` as well.
const api = new Zodios([getUser, createUser])
ecyrbe commented 2 years ago

Hello, Thank you for the feedback,

This already possible with apiBuilder. Maybe it's not clear enough in the docs that this is possible to split definitions:

// getUser.ts

export default apiBuilder({
  method: "get",
  path: "/users/:id",
  alias: "getUser",
  description: "Get a user",
  response: z.object({
    id: z.number(),
    name: z.string(),
  }),
}).build();
// createUser.ts

export default apiBuilder({
  method: "post",
  path: "/users",
  alias: "createUser",
  description: "Create a user",
  parameters: [{
    name: 'body',
    type: 'Body',
    schema: z.object({
      name: z.string(),
    })
  }],
  response: z.object({
    id: z.number(),
    name: z.string(),
  }),
}).build();
// api.ts
import getUser from './getUser';
import createUser from './createUser';

const api = new Zodios([...getUser, ...createUser]);

You can check dev.to for a full example. And documentation

Anyway, i think it's a good idea to also have a dedicated helper to create an individual endpoint only and this way evoid using the spread operator to combine them.

Will do!

ecyrbe commented 2 years ago

Done!

Check Release v9.2.0 And documentation : https://www.zodios.org/docs/api/helpers#makeendpoint

Todomir commented 2 years ago

Wow, talk about blazingly fast. Thanks :rocket:

ecyrbe commented 2 years ago

if not already, consider giving zodios project a star, it helps the project to be improved to make it known as it means more feedback like yours.