🇺🇸English |
🇯🇵日本語
aspida
Type safe HTTP client for the browser and node.js.
Fetures
- CLI that generates a TS file that can define types for path, URL query, header, body, and response.
- The return value is an axios response object
- baseURL and common header can be set with axios
Procedure
- Reproduce the endpoint directory structure in the apis directory
- Export Methods interface with TS file
- Call 'aspida --build' with npm scripts
- API type definition file 'apis/$api.ts' will be generated, so import the application and make an HTTP request
Getting Started
Installation
Create apis directory
$ mkdir apis
Create an endpoint type definition file
-
GET: /v1/users/?limit={number}
-
POST: /v1/users
apis/v1/users/index.ts
interface User {
id: number
name: string
}
export interface Methods {
get: {
params?: {
limit: number
}
response: User[]
}
post: {
data: {
name: string
}
response: User
}
}
-
GET: /v1/users/${userId}
-
PUT: /v1/users/${userId}
apis/v1/users/_userId@number.ts
Specify the type of path variable “userId” starting with underscore with “@number”
If not specified with @, the default path variable type is "number | string"
interface User {
id: number
name: string
}
export interface Methods {
get: {
response: User
}
put: {
data: {
name: string
}
response: User
}
}
Build type definition file
package.json
{
"scripts": {
"api:build": "aspida --build"
}
}
$ npm run api:build
> apis/$api.ts was built successfully.
Make HTTP request from application
src/index.ts
import api from "../apis/$api"
;(async () => {
const userId = 0
const limit = 10
await api().v1.users.post({ name: "mario" })
const res = await api().v1.users.get({ params: { limit } })
console.log(res)
const user = await api()
.v1.users._userId(userId)
.$get()
console.log(user)
})()
Examples
See examples for source code.
Tips
Set baseURL
src/index.ts
import axios from "axios"
import api from "../apis/$api"
axios.defaults.baseURL = "http://localhost:8080"
;(async () => {
const limit = 10
await api().v1.users.post({ name: "mario" })
const res = await api().v1.users.$get({ params: { limit } })
console.log(res)
})()
src/index.ts
import axios from "axios"
import api from "../apis/$api"
axios.defaults.headers.common["X-Auth-Token"] = "YOUR TOKEN"
;(async () => {
const userId = 0
const limit = 10
await api().v1.users.post({ name: "mario" })
const user = await api()
.v1.users._userId(userId)
.$get()
console.log(user)
})()
Request using axios Instance
src/index.ts
import axios from "axios"
import api from "../apis/$api"
;(async () => {
const limit = 10
const client = axios.create({ baseURL: "http://localhost:10000" })
const $api = api(client)
await $api.v1.users.post({ name: "mario" })
const res = await $api.v1.users.$get({ params: { limit } })
console.log(res)
})()
Contribution
Build
npm install
npm run build
node ./bin/index.js --build
if you want to watch file changes and rebuild automatically,
you can use --watch
instead of --build
License
Aspida is licensed under a MIT License.