Dealing with Inconsistent Internal API Responses

Photo by Susan Q Yin on Unsplash

Dealing with Inconsistent Internal API Responses

Intro

I had to deal with my inconsistent API responses, that was such a headache and counterproductive. When an API returns different shapes of data (e.g., “msg,” “message,” or “error”), handling responses will be inconsistent, and inconsistency leads to bugs, and bugs lead to more troubles.

The Generic Type Solution

Your solution of creating a generic type, inspired by Supabase, is a smart approach. Let’s break down the type you’ve defined:

type ResponseState<
    Data extends Record<string, unknown> = Record<string, unknown>,
    Error extends Record<"message", string> = Record<"message", string>,
> =
    | {
        data: Data;
        error: null;
    }
    | {
        data: null;
        error: Error;
    };

Here’s what each part does:

  1. Type Parameters (Data and Error):

    • Data: Represents the successful response data. It’s a generic type that can hold any shape of data (hence Record<string, unknown>).

    • Error: Represents the error response. It’s constrained to have a “message” property (as specified by Record<"message", string>).

  2. Union Type (ResponseState):

    • The ResponseState type combines two possibilities:

      • A successful response with data (data: Data and error: null).

      • An error response with no data (data: null and error: Error).

Benefits of Using This Type

  1. Consistency: By enforcing a consistent structure for API responses, you eliminate surprises. Consumers of your API know exactly what to expect.

Type Safety: When you handle API responses, TypeScript ensures that you’re using the correct properties and types. No more run-time surprises!

Now the generic type is a part of the indie-starter.dev boilerplate, so I don't have copy/paste it to new projects and can benefit from it too.

Remember, consistency and type safety are essential for maintaining robust codebases. Keep up the great work! 🚀


If you have any further questions or need additional details, feel free to ask! 😊