1.0.1 • Published 2 years ago

@colorfy-software/apify v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

@colorfy-software/apify

This is a simple wrapper for fetch to write less code and have stuff typed

NPM JavaScript Style Guide

Installation

$ yarn add @colorfy-software/apify

Usage

Creating a request

// api/requests.ts

import { CreateRequest, CreateRequestType } from '@colorfy-software/apify'

// Define request type
interface CreatePostReqType {
  title: string
  body: string
  userId: number
}

// Define response type
interface CreatePostResType {
  id: number
  title: string
  body: string
  userId: number
}

// Combine types
type CretePostType = CreateRequestType<CreatePostReqType, CreatePostResType>

// Create request
const createPost = new CreateRequest<CretePostType>('/posts')

// Export all requests
export default { createPost }

Creating api interface

// api/index.ts

import { APIConstructor } from '@colorfy-software/apify'

// Import requests from prev file
import requests from './requests'

// Create API function
const api = APIConstructor<typeof requests>(requests, {
  baseUrl: 'https://jsonplaceholder.typicode.com', // Can define base url
  // Can hook into life-cycle events
  onRequestStart: ({ requestName, params }) => {
    console.log('ON REQUEST START:', { requestName, params })
  },
  onSuccess: ({ requestName, response }) => {
    console.log('ON SUCCESS: ', { requestName, response })
  },
  onError: ({ requestName, error }) => {
    console.log('ON ERROR: ', { requestName, error })
  },
})

export default api

Consuming the api

// any-file.ts

import api from '../api'

// ready to be used and is all typed
api('getTodo', {
  userId: 1,
  body: 'This be a post',
  title: 'This be the title of the post',
}).then((res) => {
  const { body, userId, title, id } = res
})