npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@smg-automotive/api-client-pkg

v4.4.0

Published

Simple wrapper with convenience features to connect to your favorite API

Downloads

1,326

Readme

api-client-pkg

CircleCI semantic-release

Usage

npm install @smg-automotive/api-client-pkg

Creating a client

Create a new typescript file and define an interface that describes your API. The interface must extend ClientConfiguration. The key defines the path to the API (use curly brackets for dynamic parameters) and the values define available methods for that path.

import {
  ApiClient,
  ClientConfiguration,
  RequestType,
  ResponseType,
} from '@smg-automotive/api-client-pkg';

interface ComparisonClientConfiguration extends ClientConfiguration {
  'users/me/listing-comparisons': {
    get: () => ResponseType<ListingComparison[]>;
    post: (
      request: RequestType<ListingComparison>
    ) => ResponseType<ListingComparisonCreateResponse>;
  };
  'users/me/listing-comparisons/{listingComparisonId}': {
    put: (request: RequestType<ListingComparison>) => ResponseType;
    delete: (request: RequestType) => ResponseType;
    get: (request: RequestType) => ResponseType<ListingComparison>;
  };
}

export const comparisonClient = ApiClient<ComparisonClientConfiguration>({
  baseUrl: 'https://api.automotive.ch/api',
  headers: {
    // your custom headers
  },
});

Each client needs to be configured by its own. The default values are:

| property | type | default | | -------- | ------ | -------------------------------------- | | baseUrl | string | "" | | headers | object | { 'Content-Type': 'application/json' } |

If you pass a custom configuration for a single API call with the RequestType object, the configuration is merged/overwritten.

await comparisonClient
  .path('users/me/listing-comparisons/{listingComparisonId}', {
    listingComparisonId: 1234,
  })
  .get({
    options: {
      baseUrl: 'https://someCustomBaseUrlForThatApi',
      headers: {
        // your custom headers
      },
      accessToken: 'your token',
    },
  });

Paginated requests

Backend APIs may implement standardized paginated endpoints. You can use the following helper types to type the request and response for an API providing paginated content.

interface VersionsClientConfiguration extends ClientConfiguration {
  'versions/search': {
    post: (
      request: RequestType<PaginatedQuery<VersionBody>, never>
    ) => ResponseType<never, PaginatedResponse<Version>>;
  };
}

Using the client

Depending on your client configuration, you are going to get typing for the request and the response body. The body is parsed and transformed to an object by the client.

const response = await comparisonClient
  .path('users/me/listing-comparisons/{listingComparisonId}', {
    listingComparisonId: 1234,
  })
  .get();

if (response.ok) {
  // response.body is typed to ListingComparison
} else {
  // something failed
}

If you are using curly brackets for the dynamic parameters, you also get typing for the path parameters. Furthermore, the api client replaces those occurrences automatically for you.

await comparisonClient
  // this will fail with "Property 'listingComparisonId' is missing"
  .path('users/me/listing-comparisons/{listingComparisonId}', {})
  .get();

await comparisonClient
  // this will call fetch with https://yourBaseUrl.ch/users/me/listing-comparisons/1234
  .path('users/me/listing-comparisons/{listingComparisonId}', {
    listingComparisonId: 1234,
  })
  .get();

Authorization

You can pass accessToken to the request options if you are talking to a protected API. The client will automatically set the header with a Bearer token.

// fetch is called with the header { Authorization: `Bearer ${accessToken}` }
await comparisonClient
  .path('users/me/listing-comparisons/{listingComparisonId}', {
    listingComparisonId: 1234,
  })
  .get({
    options: {
      accessToken: authHeader.accessToken,
    },
  });

Data sanitization

In case you need to sanitize data for a certain path or method you can pass sanitizers via the client configuration:

type Image = { s3Key: string };

type Listing = {
  images: Image[];
  make: string;
  model: string;
};

const sanitizeListing = ({ images, make, model }: Listing) => ({
  images: images || [],
  make: make || 'default make',
  model: model || 'default model',
});

interface ListingClientConfiguration extends ClientConfiguration {
  '/listings/{listingId}': {
    get: () => ResponseType<object, Listing>;
  };
}

export const listingClientWithSanitizers =
  ApiClient<ListingClientConfiguration>({
    baseUrl: 'https://api.automotive.ch/api',
    sanitizers: {
      '/listings/{listingId}': {
        get: sanitizeListing,
      },
    },
  });

This would apply the sanitizer for every get request on /listing/{listingId} path. It can be useful when you want to ensure some basic and sane defaults that cannot be guaranteed by the backend service.

Error handling

The promise is not rejected if any error occurs on API level ( see fetch documentation for reference). You can check for response.ok to know whether the request was successful or not and to get typing on the body object.

const response = await comparisonClient
  .path('users/me/listing-comparisons/{listingComparisonId}', {
    listingComparisonId: 1234,
  })
  .get({
    options: {
      accessToken: authHeader.accessToken,
    },
  });

if (response.ok) {
  // it worked!
} else {
  // it did not work for some reason
  if (response.status === 401) {
    // it did not work because user is not authorized!
  }
}

Testing

Create a file in the __mocks__ directory called @smg-automotive/api-client-pkg.ts with the following content:

export { ApiClient } from '@smg-automotive/api-client-pkg/dist/__mocks__/index';

By default, all the API calls will succeed and return an empty body. If you want to return a specific value you can do this by setting a spy on the created client:

import { comparisonClient } from '~/clients/userListingComparison';

jest.spyOn(comparisonClient, 'path').mockReturnValueOnce({
  get: jest.fn().mockReturnValueOnce(
    Promise.resolve({
      status: 401,
      body: { error: 'Unauthorized' },
      ok: false,
    })
  ),
});

if you want to overwrite the mock behavior of all used api-client functions in your test file, you can also use jest.mock for it:

jest.mock('@smg-automotive/api-client-pkg', () => ({
  ApiClient: () => ({
    path: () => {
      return {
        get: jest.fn().mockReturnValue(
          Promise.resolve({
            status: 401,
            body: { error: 'Unauthorized' },
            ok: false,
          })
        ),
        post: jest.fn(),
        put: jest.fn(),
        delete: jest.fn(),
      };
    },
  }),
}));

Development

npm run build

You can link your local npm package to integrate it with any local project:

cd smg-automotive-example-pkg
npm run build

cd <project directory>
npm link ../smg-automotive-example-pkg

Release a new version

New versions are released on the ci using semantic-release as soon as you merge into master. Please make sure your merge commit message adheres to the corresponding conventions.