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

@opengeoweb/api

v9.37.0

Published

GeoWeb API library for the opengeoweb project

Downloads

2,278

Readme

current version coverage

content

Table of contents generated with markdown-toc

Api

This library was generated with Nx. The api lib makes it possible to use ApiProvider to wrap your components and make the api accessible by using the useApiContext hook.

Running unit tests

Run nx test api to execute the unit tests via Jest.

Setup the api

1. Define a type for the api.

Create a file called api, and create a type for the api. This should be a type that returns promises. Example:

// api.ts
export type AppApi = {
  getInitialPresets: (
    config: ConfigType,
  ) => Promise<{ data: InitialAppPreset }>;
  getScreenPresets: (
    config: ConfigType,
  ) => Promise<{ data: WorkspacePreset[] }>;
  getBeVersion: () => Promise<{ data: { version: string } }>;
};

2. Define routes for your api.

This should be a method that returns the routes. Example:

// api.ts
const getApiRoutes = (axiosInstance: AxiosInstance): AppApi => ({
  getInitialPresets: (
    formData: FormData,
  ): Promise<{ data: InitialAppPreset }> => {
    return axiosInstance.get('/getInitialPresetsUrl', formData);
  },
  getScreenPresets: (
    formData: FormData,
  ): Promise<{ data: WorkspacePreset[] }> => {
    return axiosInstance.get('/getScreenPresets', formData);
  },
  getBeVersion: (): Promise<{ data: { version: string } }> => {
    return axiosInstance.get('/version');
  },
});

3. Create a createApi method to initiate the api

At GeoWeb we use axios to do request to apis. Since we also need authentication, we can't use our defined api directly, so create a small helper method to combine the axiosInstance with our api:

// api.ts
import { createApiInstance } from '@opengeoweb/api';

export const createApi = ({
  url: string,
  appURL: string,
  auth: Credentials,
  setAuth: (cred: Credentials) => void,
  authTokenURL: string,
  authClientId: string,
}): AppApi => {
  const axiosInstance = createApiInstance(
    url,
    appURL,
    auth,
    setAuth,
    authTokenURL,
    authClientId,
  );

  return getApiRoutes(axiosInstance);
};

4. Define a baseURL inside config.json

Your api needs a baseURL in order to work. Add this key to the config.json. Be aware, this involves more changes in other repositories. Example:

// config.json
{
   ...
  "GW_MY_NEW_TEST_API_URL": 'https://mynewapi.com/v3'
}

5. Define a fakeApi.

Since storybook can't handle authenthication we need to mock the api with dummy data locally. It's also nice for testing functionality out without to have the geoweb app running. Create a new file called fakeApi, and add the same apiRoutes but let it return dummy data. Example:

// fakeApi.ts
export const createFakeApi = (): AppApi => {
  const api = {
    // dummy calls
    getInitialPresets: (): Promise<{ data: InitialAppPreset }> =>
      Promise.resolve({
        data: defaultInitialPresets as InitialAppPreset,
      }),
    getScreenPresets: (): Promise<{
      data: WorkspacePreset[];
    }> =>
      Promise.resolve({
        data: defaultScreenPresets as WorkspacePreset[],
      }),
    getBeVersion: (): Promise<{ data: { version: string } }> =>
      Promise.resolve({ data: { version: 'version 1.0.1' } }),
  };

  return api;
};

Also create a createApi method. Since we're not doing real requests with axios with this, we won't need it and use the fakeAxiosInstance. Example:

// fakeApi.ts
import { createFakeApiInstance } from '@opengeoweb/api';
export const createApi = (): TafApi => {
  const instance = createFakeApiInstance();
  return getApiRoutes(instance);
};

How to use the api

If you follow the steps above, you end up with 2 new files (api.ts and fakeApi.ts) and a new config key for the json.

Use api inside app for production (api.ts)

If you want to try the api out with real data, you should do this inside the app. First, wrap the component which needs the api with the ApiProvider, and pass the createApi method from the api:

// app/geoweb/components/MyNewModule
  <ApiProvider
      baseURL={config.GW_MY_NEW_TEST_API_URL}
      appURL={config.GW_APP_URL}
      auth={auth}
      onSetAuth={onSetAuth}
      createApi={createApi} // coming fron api.ts
      authTokenURL={config.GW_AUTH_TOKEN_URL}
      authClientId={config.GW_AUTH_CLIENT_ID}
    >
      <ErrorBoundary>
        <MyNewModule />
      </ErrorBoundary>
    </ApiProvider>

The baseURL should get the url you've defined earlier. The createApi should pass the createApi method we've defined. The rest of the props you can pass from the props of geoweb.

Use (fake)api inside libs for storybook

If you want to try the api out with fake data, you should do this inside storybook. First, wrap the component which needs the api with the ApiProvider. and pass the createApi method from the fakeApi:

// libs/myNewLib/src/lib/MyNewLibDemo.stories.tsx
  <ApiProvider
      createApi={createApi} // coming fron fakeApi.ts
    >
      <ErrorBoundary>
        <MyNewModule />
      </ErrorBoundary>
    </ApiProvider>

Use the useApiContext inside a component to access the api or fakeApi

Inside your component you can use the useApiContext to access the defined routes. Please note that the ApiProvider needs to be used around one of the parent components for this to work. Any story or tests should therefore also be wrapped:

const MyComponent: React.FC = () => {
  const { api } = useApiContext<AppApi>();
  const [initialPresets, setInitialPresets] = React.useState<InitialAppPreset>([]);

  React.useEffect(()=> {
    const intitialPresets = await api.getInitialPresets(myFormvalues);
    setInitialAppPresets(intitialPresets);
  }, []);

  return <>initialPresets.map(preset => preset.name)</>
};

export const StoryBookExample = (): React.ReactElement => (
  <ApiProvider
    createApi={createApi} // coming fron fakeApi.ts
  >
      <ErrorBoundary>
        <MyComponent />
      </ErrorBoundary>
  </ApiProvider>
);