このライブラリはTypeScriptでRestAPIを型安全に使う為のAPI Clientを提供します。
import { apiClient } from "strictcat"
type Schema = {
resource: {
"/hello": {
GET: {
response: {"message": "hello"};
};
};
"/echo": {
POST: {
body: {
"message": string
}
response: {"message": string}
}
}
};
};
const api = apiClient<Schema>("https://develop.sankosc.co.jp/apitest/api")
api.call('GET', "/hello").then((res) => {
if (res.type === 'succeeded'){
console.log(res.data.message)
}
})
api.call("POST", "/echo", { body: { message: "hello world" }}).then((res) => {
if (res.type === 'succeeded'){
console.log(res.data.message)
}
})
最初にapiClientを初期化する際に渡すことで、全てのリクエストに対して同様のbodyを付与することが出来ます
apiClient<Schema>("", "POST", {
sharedBody: { token: "xxxxx" },
});
指定したAPIのレスポンスが成功していると保証します。
import { apiClient, assertIsSuccess } from "strictcat"
type Schema = {
resource: {
"/hello": {
GET: {
response: {"message": "hello"};
};
};
"/echo": {
POST: {
body: {
"message": string
}
response: {"message": string}
}
}
};
};
const api = apiClient<Schema>("https://develop.sankosc.co.jp/apitest/api")
api.call('GET', "/hello").then((res) => {
assertIsSuccess(res)
console.log(res.data.message)
})
都度変更する場合は以下のようにheaderを指定してください
await api.call('POST', '/api/re', {headers: {'Content-type': 'application/json'}, body: {text: 'hello world'}})
全体で変更する場合は以下のようにApiClientの呼び出し方を変更してください
const api = apiClient<Schema>("https://develop.sankosc.co.jp/apitest/api", "application/json")
MDN からの引用になりますが、credentialsがinclude
になっていないと設定されません。
credentials オプションを include に設定しない限り、fetch() は次のように動作します。
- オリジン間リクエストではクッキーを送信しません。
- オリジン間のレスポンスでは、送り返されたクッキーを設定しません。
- 2018 年 8 月現在、既定の資格情報ポリシーは same-origin に変更されています。 Firefox もバージョン 61.0b13 で変更されました)。
以下のように変更してください
await api.call('POST', '/api/auth/signin', {credentials: 'include', headers: {'content-type': 'application/json'}}, {username, password})
このlibraryは 強力な型補完を行うRestAPI ClientをTypeScriptで実装した というWHITE PLUS TechBlog様の記事を参考に作成したライブラリです。 問題があった際はissue等にご連絡ください。