Skip to content

Consider replacing axios with fetch #2

Open
@maxfi

Description

@maxfi

Frameworks like Next.js and Remix polyfill fetch on the server and fetch is also coming to node.

Replacing axios with fetch would decrease the package size which could be helpful in serverless environments to decrease cold start times.

Possible implementation:

   /**
   * Execute a API action.
   * @link https://docs.atlas.mongodb.com/api/data-api-resources/
   */
  public async $$action<Result = any>(
    name: string,
    params: BaseParams = {}
  ): Promise<Result> {
    const mergedParams = {
      ...this.#baseParams,
      ...params,
    };

    if (
      !mergedParams.dataSource ||
      !mergedParams.database ||
      !mergedParams.collection
    ) {
      throw new Error("Invalid params: dataSource, database, collection");
    }

    const API_KEY_FIELD = "api-key";

    const url = this.#config.urlEndpoint
      ? getActionUrl(this.#config.urlEndpoint, name)
      : getActionUrl(
          getUrlEndpoint(this.#config.appId!, this.#config.region),
          name
        );

    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Request-Headers": "*",
        [API_KEY_FIELD]: this.#config.apiKey,
      },
      body: JSON.stringify(mergedParams),
    });
    if (!response.ok) {
      // https://docs.atlas.mongodb.com/api/data-api-resources/#error-codes
      const errorJSON = await response.json();
      errorJSON.config.headers[API_KEY_FIELD] = "*****";
      throw errorJSON;
    }
    const result: Result = await response.json();
    return result;
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions