Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a schema option to the options object #28

Closed
d-a-ve opened this issue Jun 23, 2024 · 0 comments · Fixed by #29
Closed

Add a schema option to the options object #28

d-a-ve opened this issue Jun 23, 2024 · 0 comments · Fixed by #29
Labels

Comments

@d-a-ve
Copy link

d-a-ve commented Jun 23, 2024

Feature:

Adding an option where consumers can pass a schema to be used for validating the response from the request.

Reason:

This option will give consumers the guarantee of the response matching the schema provided and that their application will not break due to a change in the response structure.

Example:

This is an example code snippet from a replication of the API call request with an option to pass a schema.

export async function apiCall<T>(args: {
  url: `/${string}`;
  method: AxiosRequestConfig["method"];
  data?: Record<string, unknown>;
  params?: Record<string, unknown>;
  schema: ZodSchema<T>;
}): Promise<SuccessResponse<T>> {
  const { url, method, data, params, schema } = args;
  try {
    const res = await $http.request<T>({
      url,
      method,
      data,
      params,
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });
    const parsed = schema.parse(res.data);
    return { success: true, data: parsed };
  } catch (e: unknown) {
    if (e instanceof AxiosError) {
      throw {
        success: false,
        error: {
          message: e.response?.data.message || "An error occurred",
          status: e.response?.status || 500,
        },
      };
    }

    if (e instanceof ZodError) {
      throw {
        success: false,
        error: {
          message: "Something went wrong, please try again later!",
          status: 500,
        },
      };
    }

    throw {
      success: false,
      error: {
        message: "An error occurred",
        status: 500,
      },
    };
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
1 participant