Zodios: 컴파일 시간과 런타임 모두에서 유형 검사가 가능한 오픈 소스 HTTP 클라이언트(2/3부)
                                            
                                                
                                                
                                                
                                                
                                                
                                                 22507 단어  axioshttptypescriptzodios
                    
참고로 Zodios은 유형과 유효성 검사 스키마를 모두 작성할 필요 없이 런타임(zod 유효성 검사) 및 컴파일 시간(typescript)에 유형 검사를 수행하는 오픈 소스 HTTP 클라이언트입니다.
API 선언을 한 번만 작성하면 완료됩니다.
이 후속 조치에서는 삶을 더 쉽게 만들어 줄 수 있는 Zodios의 몇 가지 기능을 살펴보겠습니다.
별칭 끝점
이전 버전의 zodios를 사용할 때는 API를 선언할 때와 사용할 때 모두 자신을 반복하고 PATH를 다시 작성할 수밖에 없었습니다.
가독성에는 좋지만 일부 사용 사례에서는 반복하는 것이 지루할 수 있습니다.
사용자가 보낸 문제에서 이 예를 확인하십시오.
const MY_ORG = 'my-org-id' as const; // user wanted to extract his organization ID from the declaration
const client = new Zodios(BASE_API_URL, [
  {
    method: 'get',
    path: `/v1/organizations/${MY_ORG}/shipments`,
    response: schipmentSchema
  }
] as const)
그런 다음 이 API를 호출하려면 다음을 수행해야 합니다.
const shipments = await client.get(`/v1/organizations/${MY_ORG}/shipments`);
이제 zodios를 사용하여 별칭을 선언할 수 있습니다.
const MY_ORG = 'my-org-id' as const; // if your org changes you only need to change it once here
const client = new Zodios(BASE_API_URL, [
  {
    method: 'get',
    path: `/v1/organizations/${MY_ORG}/shipments`,
    alias: 'getOrgShipments',
    response: schipmentSchema
  }
] as const)
그런 다음 사용하려면 다음을 수행하십시오.
const shipments = await client.getOrgShipments();
더 이상 자신을 반복할 필요가 없습니다.
CRUD 도우미
이 기능은 모든 요구 사항에 적합하지 않을 수 있지만 간단한 CRUD 선언이 있는 경우
asCrudApi() 도우미를 사용하여 자신을 반복하지 않을 수 있습니다.더 복잡한 API가 있지만 엔드포인트가 표준화된 경우 고유한 헬퍼를 생성할 수 있습니다.
asCrudApi() implementation에서 영감을 얻으십시오.import { Zodios, asCrudApi } from '@zodios/core';
const userSchema = z.object({
  id: z.number(),
  name: z.string(),
});
const apiClient = new Zodios(BASE_URL, 
asCrudApi('user',userSchema));
이는 보다 장황한 선언과 동일합니다.
const apiClient = new Zodios(BASE_URL, [
  {
    method: "get",
    path: "/users",
    alias: "getUsers",
    description: "Get all users",
    response: z.array(userSchema),
  },
  {
    method: "get",
    path: "/users/:id",
    alias: "getUser",
    description: "Get a user",
    response: userSchema,
  },
  {
    method: "post",
    path: "/users",
    alias: "createUser",
    description: "Create a user",
    parameters: [
      {
        name: "body",
        type: "Body",
        description: "The object to create",
        schema: userSchema.partial(),
      },
    ],
    response: userSchema,
  },
  {
    method: "put",
    path: "/users/:id",
    alias: "updateUser",
    description: "Update a user",
    parameters: [
      {
        name: "body",
        type: "Body",
        description: "The object to update",
        schema: userSchema,
      },
    ],
    response: userSchema,
  },
  {
    method: "patch",
    path: "/users/:id",
    alias: "patchUser",
    description: "Patch a user",
    parameters: [
      {
        name: "body",
        type: "Body",
        description: "The object to patch",
        schema: userSchema.partial(),
      },
    ],
    response: userSchema,
  },
  {
    method: "delete",
    path: "/users/:id",
    alias: "deleteUser",
    description: "Delete a user",
    response: userSchema,
  },
] as const);
또한 모든 CRUD 끝점에 대한 별칭이 자동 생성되는 것을 볼 수 있습니다.
따라서 엔드포인트를 호출할 수 있습니다.
const users = await client.getUsers();
반응 후크
Zodios에는 일부 React Hooks도 있습니다. 무대 뒤에서 Zodios는 react-query을 사용하고 있습니다.
후크에 별칭을 사용할 수도 있습니다.
use<Alias> 접두사가 자동으로 붙습니다.예를 들어 별칭
getUsers은 useGetUsers 후크와 함께 사용할 수 있습니다.import React from "react";
import { Zodios } from "@zodios/core";
import { ZodiosHooks } from "@zodios/react";
import { z } from "zod";
const baseUrl = "https://jsonplaceholder.typicode.com";
const userSchema = z
  .object({
    id: z.number(),
    name: z.string(),
  });
const zodios = new Zodios(baseUrl, asCrudApi('user',userSchema));
const zodiosHooks = new ZodiosHooks("jsonplaceholder", zodios);
const Users = () => {
  const {
    data: users,
    isLoading,
    error,
    invalidate: invalidateUsers, // zodios also provides invalidation helpers
  } = zodiosHooks.useGetUsers();
  const { mutate } = zodiosHooks.useCreateUser(undefined, {
    onSuccess: () => invalidateUsers(),
  });
  return (
    <>
      <h1>Users</h1>
      <button onClick={() => mutate({ name: "john doe" })}>add user</button>
      {isLoading && <div>Loading...</div>}
      {error && <div>Error: {(error as Error).message}</div>}
      {users && (
        <ul>
          {users.map((user) => (
            <li key={user.id}>{user.name}</li>
          ))}
        </ul>
      )}
    </>
  );
};
결론
오늘은 그게 전부입니다. Zodios는 여전히 진화하고 있습니다. Zodios에서 확인하고 싶은 사용 사례가 있는 경우 github에서 문제를 생성하거나 풀 요청으로 기여하십시오.
zodios이 마음에 드신다면 이 기사에 좋아요를 누르는 것을 잊지 마세요.
Reference
이 문제에 관하여(Zodios: 컴파일 시간과 런타임 모두에서 유형 검사가 가능한 오픈 소스 HTTP 클라이언트(2/3부)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/ecyrbe/zodios-an-open-source-http-client-with-type-checking-at-both-compile-time-and-runtime-part-23-2j41텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)