@chotot/api-kit
v2.2.0
Published
<p align="center"> <img src="https://user-images.githubusercontent.com/93700515/229010828-187b74d5-e0c0-42e9-a160-c531d24fdcef.gif" alt="Chotot API Kit logo"> </p>
Readme
:blossom: Chotot API Kit is a unifying solution for communication with Chotot REST API. The kit is built with Decomposable architecture in mind, which means you use only the code you need. You can build your own custom api kit in only a few lines of code. Make your own tradeoff between functionality and bundle size.
Installation
pnpm add @chotot/api-kitNext.js >= v13
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
transpilePackages: ['@chotot/api-kit'],
}
module.exports = nextConfigNext.js < v13 with next-transpile-modules
pnpm add next-transpile-modules// next.config.js
const withTM = require('next-transpile-modules')(['@chotot/api-kit']);
/** @type {import('next').NextConfig} */
const nextConfig = {}
module.exports = withTM(nextConfig);Quickstart
Create a ak.ts file and put it in wherever you like. For example src/helpers/ak.ts
// ak.ts
import { ApiKit, ProfileEndpoints, CustomApiKitConfig } from '@chotot/api-kit'
class CustomApiKit extends ApiKit {
profile: ProfileEndpoints
constructor(params: CustomApiKitConfig) {
super(params)
const econf = this.getEndpointConfig()
this.profile = new ProfileEndpoints(econf)
}
}
export const ak = new CustomApiKit({
env: 'dev',
})Then use it in any where you like. For example:
import { ak } from '~/helpers/ak'
const AboutPage = () => {
useEffect(() => {
ak.profile.getProfileSelf().then(res => console.log(res))
}, [])
return <div>About</div>
}How to add a new endpoint
Add a new endpoint to an existing plugin
Each endpoint will be a method of the class. A general method is:
async getSomething(inputs: Types.GetSomethingInputs): Promise<Types.GetSomethingOutputs> {}Inputs
Each method will accept an inputs with the structure:
interface Inputs {
fragments: {}
params: {}
body: {}
headers: {}
}The
fragmentswill be used for constructing theurl, for example:/todos/update/{todo_id}/the{todo_id}will be placed in thefragmentsobjectThe
paramswill be used for the query string, for example:/todos/list?title=something, thetitle=somethingwill be placed in theparamsobjectThe
bodywill be the request bodyThe
headerswill be used for the request header
Outputs
Calling the API Endpoints, then taking the JSON respone and convert them into an interface using this tool: https://transform.tools/json-to-typescript
interface Outputs {}These interfaces Inputs and Outputs will be put into the types.ts file along with every endpoint file.
Add a new plugin
- Add plugin
Following the naming convention when adding a new plugin, we will mapping 1:1 with the API Endpoint URL, for example:
/v2/private/cart/service: the plugin will be folderCartin thepluginsfolder -->/plugins/Cart/private/api-uni/v1/lead/search-ad-info: the plugin will be folderLeadin theApiUniin thepluginsfolder -->/plugins/ApiUni/Lead
In each plugin, we will have an index.ts file and an types.ts file:
plugins
│
└───ApiUni
│ │
│ └───Subscription
│ │ index.ts
│ │ types.ts
│
└───Cart
│ index.ts
│ types.ts- Export plugin
In the plugins/index.ts file, export the new plugin:
export { CartEndpoints } from './Cart'- Export types
In the plugins/types.ts file, export the types of the new plugin, following the conventions, for example:
import * as ICart from './Cart/types'
export {
...
ICart
}- Add your new plugin to the
ApiKitFull.ts
Usage
The Chotot API Kit can be used in two ways:
Full Kit
This instance will contains all the supported API endpoints, this is fast to setup, easy to use, however it comes with a cost - bundle size. Since all plugins (endpoints) are included, you will end up with endpoints that you don't use.
// src/helpers/akFull.ts
import { ApiKitFull } from '@chotot/api-kit'
export const ak = new ApiKitFull({
env: 'dev',
})
Custom Kit
The API Kit is designed so that the user can easily create their own kit. By picking up only plugins that they need, they will only pay (the bundle size) for what they use.
// src/helpers/ak.ts
import {
ApiKit,
LeadEndpoints,
PartnerPortalEndpoints,
ProfileEndpoints,
ShopsEndpoints,
shouldPersistToken,
SubscriptionEndpoints,
CustomApiKitConfig
} from '@chotot/api-kit'
class CustomApiKit extends ApiKit {
profile: ProfileEndpoints
shops: ShopsEndpoints
apiUni: {
partnerPortal: PartnerPortalEndpoints
lead: LeadEndpoints
subscription: SubscriptionEndpoints
}
constructor(params: CustomApiKitConfig) {
super(params)
const econf = this.getEndpointConfig()
this.profile = new ProfileEndpoints(econf)
this.shops = new ShopsEndpoints(econf)
this.apiUni = {
partnerPortal: new PartnerPortalEndpoints(econf),
lead: new LeadEndpoints(econf),
subscription: new SubscriptionEndpoints(econf),
}
}
}
export const ak = new CustomApiKit({
env: 'dev',
})Constructor options
Most basic options required by the API Kit are:
Accepted values: dev, uat, prod
Setting env is required so that the API Kit knows which API Gateway to target.
The env dev will point to the https://gateway.chotot.org API Gateway.
The env prod will point to the https://gateway.chotot.com API Gateway.
const ak = new ApiKit({
env: "dev",
});Built-in Features
| Feature | Supported | |----------------------------------------------|-----------| | Auto refresh token on unauthentication error | ✅ | | Dedup refresh token requests | 🏗️ | | Using Fetch API | 🏗️ | | Background refresh token before expired | 🏗️ |
Currently, the API Kit supports one built-in feature: auto refresh token on unauthentication error.
// src/helpers/ak.ts
import {
ApiKit,
shouldPersistToken,
} from '@chotot/api-kit'
export const ak = new CustomApiKit({
env: env === 'production' ? 'prod' : 'dev',
features: {
autoRefreshTokenOnUnauthError: {
enabled: true,
onSuccess: (outputs) => {
const { idToken, privateToken, refreshToken } = outputs
if (shouldPersistToken(Cookies.get('privateToken') ?? '', privateToken)) {
Cookies.set('privateToken', privateToken, cookieOptions)
Cookies.set('refreshToken', refreshToken, cookieOptions)
if (idToken) Cookies.set('idToken', idToken, cookieOptions)
}
},
onError: () => {
if (isDev) return
const continueUrl = window.location.href
const chototIdLogin = `https://id.chotot.${baseDomain}/login?continue=${encodeURIComponent(continueUrl)}`
window.location.href = chototIdLogin
},
},
},
})The API Kit currently do not have any opinions on how the user would do to respond to the refresh token success and error cases. The user have to determine themself. In the future, we might consider to support a default option for persist the auth tokens if not provided.
Inspiration
GitHub REST API client for JavaScript
https://github.com/octokit/rest.js/
