Skip to content

@mcsb/api / Exports / BaseAPI

Class: BaseAPI<T>

An extensible API interface, used by MojangAPI and HypixelAPI.

Example

ts
type YourOptions extends APIOptions {
    apiKey: string;
}

class YourAPI extends BaseAPI<YourOptions> {

    protected genHeaders(): Headers {
        const headers = super.genHeaders();
        headers.set("Authorization", "Bearer " + this.options.apiKey);
        return headers;
    }

    protected parseOptions(options: YourOptions): NonOptional<YourOptions> {
        return Object.freeze({
            ...this.parseDefaultOptions(options),
            apiKey: options.apiKey,
        })
    }

    public async sendRequest(): Promise<string> {
        return await this.request("https://example.com/get-data", false, ResponseSchema, res => res.someStringValue);
    }
}
type YourOptions extends APIOptions {
    apiKey: string;
}

class YourAPI extends BaseAPI<YourOptions> {

    protected genHeaders(): Headers {
        const headers = super.genHeaders();
        headers.set("Authorization", "Bearer " + this.options.apiKey);
        return headers;
    }

    protected parseOptions(options: YourOptions): NonOptional<YourOptions> {
        return Object.freeze({
            ...this.parseDefaultOptions(options),
            apiKey: options.apiKey,
        })
    }

    public async sendRequest(): Promise<string> {
        return await this.request("https://example.com/get-data", false, ResponseSchema, res => res.someStringValue);
    }
}

Type parameters

NameTypeDescription
Textends APIOptionsThe type of the options that can be provided to this API. Must extend APIOptions.

Hierarchy

Table of contents

Properties

Methods

Properties

options

Protected Readonly options: Readonly<{ [P in string | number | symbol]-?: T[P] }>

The options provided to the constructor, parsed by parseOptions.

Defined in

packages/api/src/BaseAPI.ts:127

Methods

destroy

destroy(): void

Destroy this API instance, primarily by shutting down the HttpClient. Failure to do so may leave your program hanging if you do not explicitly interrupt it.

Returns

void

Defined in

packages/api/src/BaseAPI.ts:279


genHeaders

Protected genHeaders(): Headers

Generate the Headers object to be sent with requests to the API.

Returns

Headers

A Headers instance with all the headers to send with requests.

Example

ts
protected genHeaders(): Headers {
    const headers = super.genHeaders();
    headers.set("Authorization", "Bearer " + this.options.apiKey);
    return headers;
}
protected genHeaders(): Headers {
    const headers = super.genHeaders();
    headers.set("Authorization", "Bearer " + this.options.apiKey);
    return headers;
}

Defined in

packages/api/src/BaseAPI.ts:168


parseOptions

Protected Abstract parseOptions(options): Readonly<{ [P in string | number | symbol]-?: T[P] }>

Parse the options input into the constructor into a structurally identical object but with all unset values set to their default.

Parameters

NameType
optionsT

Returns

Readonly<{ [P in string | number | symbol]-?: T[P] }>

Remarks

Within this method call parseDefaultOptions to parse the options set within APIOptions. Any additional values you have in your extensions to these options must be parsed by you.

Example

ts
protected parseOptions(options: YourOptions): NonOptional<YourOptions> {
    return Object.freeze({
        ...this.parseDefaultOptions(options),
        apiKey: options.apiKey,
    })
}
protected parseOptions(options: YourOptions): NonOptional<YourOptions> {
    return Object.freeze({
        ...this.parseDefaultOptions(options),
        apiKey: options.apiKey,
    })
}

Defined in

packages/api/src/BaseAPI.ts:154


rawRequest

Protected rawRequest(url): Promise<RawResponse>

Send a request to a given URL using this APIs HttpClient provided options. If the HttpClient has a cached response, then that response is returned immediately. Otherwise, we send a new request to the URL. Before sending the request, if an IDeferPolicy was provided to options, the defer policy is polled first.

Parameters

NameTypeDescription
urlstringThe complete URL to send a request to. Relative URLs are not supported.

Returns

Promise<RawResponse>

A Promise which resolves to a RawResponse from the API.

Throws

  • Error if the HTTP request fails

See

request

Defined in

packages/api/src/BaseAPI.ts:184


request

Protected request<S, V>(url, raw, schema?, mutator?): Promise<RawResponse>

Send an API request to the given URL using the provided HttpClient and IDeferPolicy.

Type parameters

NameType
Sextends ZodType<any, ZodTypeDef, any>
VV

Parameters

NameTypeDescription
urlstringURL to send the request to. Relative URLs not supported.
rawtrueWhether to receive a RawResponse.
schema?SIn this overload, this value is unused. - The Zod schema to use to parse the API response.
mutator?(input: TypeOf<S>) => VIn this overload, this value is unused. - A function that takes in the schema-parsed response and returns another value. This can also be used to perform additional validation on the response and throw an Error if it fails.

Returns

Promise<RawResponse>

  • If raw is true, the RawResponse from rawRequest is returned.
  • If raw is false and the mutator argument is undefined, the API response parsed by the provided schema is returned.
  • If raw is false and a mutator argument is provided, the value returned by the mutator is returned.

Throws

  • Error if the HTTP request fails.
  • Error if the schema parsing fails.

See

https://zod.dev/

Defined in

packages/api/src/BaseAPI.ts:219

Protected request<S, V>(url, raw, schema, mutator?): Promise<TypeOf<S>>

Send an API request to the given URL using the provided HttpClient and IDeferPolicy.

Type parameters

NameType
Sextends ZodType<any, ZodTypeDef, any>
VV

Parameters

NameTypeDescription
urlstringURL to send the request to. Relative URLs not supported.
rawfalseWhether to receive a RawResponse.
schemaSThe Zod schema to use to parse the API response.
mutator?(input: TypeOf<S>) => VIn this overload, this value is unused. - A function that takes in the schema-parsed response and returns another value. This can also be used to perform additional validation on the response and throw an Error if it fails.

Returns

Promise<TypeOf<S>>

  • If raw is true, the RawResponse from rawRequest is returned.
  • If raw is false and the mutator argument is undefined, the API response parsed by the provided schema is returned.
  • If raw is false and a mutator argument is provided, the value returned by the mutator is returned.

Throws

  • Error if the HTTP request fails.
  • Error if the schema parsing fails.

See

https://zod.dev/

Defined in

packages/api/src/BaseAPI.ts:239

Protected request<S, V>(url, raw, schema, mutator): Promise<V>

Send an API request to the given URL using the provided HttpClient and IDeferPolicy.

Type parameters

NameType
Sextends ZodType<any, ZodTypeDef, any>
VV

Parameters

NameTypeDescription
urlstringURL to send the request to. Relative URLs not supported.
rawfalseWhether to receive a RawResponse.
schemaSThe Zod schema to use to parse the API response.
mutator(input: TypeOf<S>) => VA function that takes in the schema-parsed response and returns another value. This can also be used to perform additional validation on the response and throw an Error if it fails.

Returns

Promise<V>

  • If raw is true, the RawResponse from rawRequest is returned.
  • If raw is false and the mutator argument is undefined, the API response parsed by the provided schema is returned.
  • If raw is false and a mutator argument is provided, the value returned by the mutator is returned.

Throws

  • Error if the HTTP request fails.
  • Error if the schema parsing fails.

See

https://zod.dev/

Defined in

packages/api/src/BaseAPI.ts:259

Released under the MIT License.