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

@coheia/simple-http-service

v1.3.28

Published

The SimpleHttpService class makes it easier to use http methods.

Downloads

71

Readme

Simple Http Service

npm npm bundle size npm bundle size npm

The SimpleHttpService class provides a simple way to make HTTP requests using the fetch API. The class supports GET, POST, PUT, PATCH, and DELETE methods and returns the response in JSON format, already typed. The class can also be extended to add authentication or other customizations and each method can have its behavior changed at the time of use through the requestInit.

And if you only need the most used methods and not a lot of things you won't use...

image

Table of Contents

Installation

$ npm install @coheia/simple-http-service

Import

Import the SimpleHttpService class and its related types as follow:

import SimpleHttpService, { Headers, SimpleConfigs } from '@coheia/simple-http-service'

Usage

import SimpleHttpService from '@coheia/simple-http-service'

const api = new SimpleHttpService({
  baseUrl: 'http://localhost:3001', // remove for same domain api
  baseEndpoint: 'api/v1'
})

// simple get request
const response = await api.get<YourResponseType>('your/endpoint')

type LoginBody = {
  username: string
  password: string
}
// simple destruct response
type LoginSuccess = {
  accessToken: string
}
const { accessToken } = await api.post<LoginSuccess, LoginBody>('auth/login', {
  username: 'admin',
  password: '***'
})

Configuration object

SimpleConfigs type defines the configuration object (optional) received in the SimpleHttpService class's constructor.

import { SimpleConfigs } from '@coheia/simple-http-service';

export const httpServiceConfig: SimpleConfigs = {
  baseUrl: 'http://localhost:3001', // don't add for same domain
  baseEndpoint: 'api/v1' // prefixed in every method's endpoint param
}

Override handleHeaders - JWT Example

If you need to add authentication, you can extend the SimpleHttpService class and override the handleHeaders method.

'Content-Type': 'application/json' is default in SimpleHttpService, if override handleHeaders remember to reset it, or not if you preferer other type 👏

import SimpleHttpService, { Headers, SimpleConfigs} from '@coheia/simple-http-service'

// Create a subclass called ProtectedService that extends SimpleHttpService.
class ProtectedService extends SimpleHttpService {
  private readonly token: string

  // The constructor sets the token and calls the parent class's constructor with the config param.
  constructor(token: string, config?: SimpleConfigs) {
    super(config)
    this.token = token
  }

  protected override handleHeaders(headers: Headers): Headers {
    return {
      Authorization: `Bearer ${this.token}`,
      'Content-Type': 'application/json',
      ...headers
    }
  }
}

export const TOKEN = 'your_token'
export const apiProtected = new ProtectedService(TOKEN)

Manage CRUD API - "Projects" example

The following code manages a CRUD API by creating a ProjectService class that extends a ProtectedService (the JWT example). The code removes the authorization header when the request does not require authentication, which is the case for the getProjects and getProject methods. The code also includes methods for creating, updating, and deleting projects, which make use of the ProtectedService's post, put, and delete methods.

import { ProtectedService, TOKEN } from './ProtectedService'
import { removeAuthorizationHeader } from '@coheia/simple-http-service'

const httpServiceConfig = {
  baseUrl: 'http://localhost:3001'
}

interface NewProject {
  name: string
  order?: number
}

interface Project extends NewProject {
  id: string
  created_at: string
  updated_at: string
}

class ProjectService extends ProtectedService {
  constructor() {
    super(TOKEN, {
      ...httpServiceConfig,
      baseEndpoint: '/projects'
    })
  }

  async getProjects(): Promise<Project[]> {
    return await this.get<Project[]>('/', removeAuthorizationHeader)
  }

  async getProject(id: string): Promise<Project> {
    return await this.get<Project>(`/${id}`, removeAuthorizationHeader)
  }

  async createProject(project: NewProject): Promise<Project> {
    return await this.post<Project, NewProject>('/', project)
  }

  async updateProject(id: string, project: NewProject): Promise<Project> {
    return await this.put<Project, NewProject>(`/${id}`, project)
  }

  async deleteProject(id: string): Promise<void> {
    return await this.delete<void>(`/${id}`)
  }
}

export const projectService = new ProjectService()

Same domain API

If you are using the same domain for both the API and the client, you can omit the configuration object completely, or individually baseUrl and baseEndpoint like this:

import SimpleHttpService from '@coheia/simple-http-service';

//for same domain api without baseEndpoint
const http = new SimpleHttpService();
const project = await http.get<ProjectType>('/project/10');
// GET - CLIENT_DOMAIN/project/10
// and for same domain api with baseEndpoint as api version
const http = new SimpleHttpService({ baseEndpoint: 'api/v3' });
const project = await http.get<ProjectType>('/project/10');
// GET - CLIENT_DOMAIN/api/v3/project/10

Contributing

Your contributions are always welcome! Submit a pull request with your changes or create an issue to discuss anything.

License

This package is licensed under the MIT License.