Git Product home page Git Product logo

lamernews-api-client's Introduction

Lamer News API Client

npm version

A JavaScript API client for the Lamer News API. This package exports ES modules and includes TypeScript definitions.

Note this package is still under development.

Source code is generated from the OpenAPI spec using the typescript-fetch template.

Getting Started

Install

npm install lamernews-api-client --save

Basic Usage

import { Configuration, NewsApi, SortType } from 'lamernews-api-client';

const apiConfig = new Configuration({
  basePath: 'https://echojs.com',
});

const newsApi = new NewsApi(apiConfig);

newsApi
  .getNews({
    sort: SortType.Top,
    start: 0,
    count: 30,
  })
  .then((response) => {
    console.log(response);
  });

Usage with Middleware & TypeScript

import {
  AuthApi,
  CommentsApi,
  Configuration,
  ConfigurationParameters,
  FetchParams,
  GenericResponse,
  Middleware,
  NewsApi,
  ResponseContext,
  RequestContext,
  ResponseStatus,
} from 'lamernews-api-client';

class ApiMiddleWare implements Middleware {
  public async pre(context: RequestContext): Promise<FetchParams | void> {
    return Promise.resolve(context);
  }

  public async post(context: ResponseContext): Promise<Response | void> {
    // Treat successful responses with response.status === 'err' as errors
    if (
      context.response.ok &&
      context.response.headers
        .get('content-type')
        ?.startsWith('application/json')
    ) {
      const response = (await context.response
        .clone()
        .json()) as GenericResponse;
      if (response.status === ResponseStatus.Err) {
        return Promise.reject(context.response);
      }
    }
    return Promise.resolve(context.response);
  }
}

const configParams: ConfigurationParameters = {
  basePath: 'https://echojs.com',
  middleware: [new ApiMiddleWare()],
};

const apiConfig = new Configuration(configParams);

export const apiClient = {
  newsApi: new NewsApi(apiConfig),
  commentsApi: new CommentsApi(apiConfig),
  authApi: new AuthApi(apiConfig),
};

export type ApiClient = typeof apiClient;

Authentication

Here's an example of how to authenticate, then upvote a new entry:

authApi
  .login({
    username: 'username',
    password: 'password',
  })
  .then((data) => {
    const { auth, apisecret } = data;
    document.cookie =
      'auth=' + auth + '; expires=Thu, 1 Aug 2030 20:00:00 UTC; path=/';
    return newsApi.voteNews({
      newsId: newsId,
      voteType: VoteType.Up,
      apisecret: apisecret,
    });
  });

Authentication in React Native

Similar to the previous example we need to manually set the cookie. This can be achieved by updating the api config.

First you need to expose a function to mutate the config:

const configParams = {
  basePath: 'https://echojs.com/api',
  middleware: [new ApiMiddleWare()],
};

const apiConfig = new Configuration(configParams);

export const apiClient = {
  newsApi: new NewsApi(apiConfig),
  commentsApi: new CommentsApi(apiConfig),
  authApi: new AuthApi(apiConfig),
};

export function updateApiConfig(config: ConfigurationParameters): void {
  Object.assign(configParams, config);
}

Now after a successful login, add the auth cookie header to the API config:

authApi
  .login({
    username: 'username',
    password: 'password',
  })
  .then((data) => {
    const { auth } = data;
    updateApiConfig({
      headers: {
        cookie: `auth=${auth}`,
      },
    });
  });

All subsequent requests will now include this request header containing the cookie.

React-Native's fetch implementation does not support posting a URLSearchParam instance as the body. You need to adjust the request body to stringify the URLSearchParams:

export class ApiMiddleWare implements Middleware {
  public async pre(context: RequestContext): Promise<FetchParams | void> {
    if (context.init.body instanceof URLSearchParams) {
      context.init.body = context.init.body.toString();
    }
    return Promise.resolve(context);
  }
}

lamernews-api-client's People

Contributors

badsyntax avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.