在获取时转换数据
在 RestEndpoint 的成员中转换数据:用 process() 处理响应,用 getRequestInit() 处理请求体,用 parseResponse() 处理响应头和原始响应体。要在某个 Entity 出现的任何地方(包括列表和嵌套数据)修改它的字段,请使用 Entity.process()。
如果你能掌控 API,请改为修改它发送的数据。轻量的客户端更快也更简单。这些转换适用于你无法掌控的 API。
从蛇形到驼峰
许多 API 使用 snake_case 的键。要在 TypeScript 中使用 camelCase,需要在两个方向上转换键。
import { camelCase, snakeCase } from 'lodash';
import { RestEndpoint, RestGenerics } from '@data-client/rest';
function deeplyApplyKeyTransform(obj: any, transform: (key: string) => string) {
const ret: Record<string, any> = Array.isArray(obj) ? [] : {};
Object.keys(obj).forEach(key => {
if (obj[key] != null && typeof obj[key] === 'object') {
ret[transform(key)] = deeplyApplyKeyTransform(obj[key], transform);
} else {
ret[transform(key)] = obj[key];
}
});
return ret;
}
class CamelEndpoint<O extends RestGenerics = any> extends RestEndpoint<O> {
getRequestInit(body) {
// we'll need to do the inverse operation when sending data back to the server
if (body) {
return super.getRequestInit(deeplyApplyKeyTransform(body, snakeCase));
}
return super.getRequestInit(body);
}
process(value) {
// a 204 response has no body
return value && deeplyApplyKeyTransform(value, camelCase);
}
}
反序列化字段
JSON 的类型很少,因此 API 会把许多值作为字符串发送。例如 ISO 8601 日期和高精度小数(浮点数可能有精度损失)。字符串用于展示没有问题。要用它们进行计算,比如给日期加上一段时间或将两个数相乘,就需要反序列化。
将 Entity.schema 与 Temporal.Instant 和 BigNumber 搭配使用:
import { Entity, RestEndpoint } from '@data-client/rest'; import { Temporal } from 'temporal-polyfill'; import BigNumber from 'bignumber.js'; export class ExchangePrice extends Entity { exchangePair = ''; updatedAt = Temporal.Instant.fromEpochMilliseconds(0); price = new BigNumber(0); pk() { return this.exchangePair; } static key = 'ExchangePrice'; static schema = { updatedAt: Temporal.Instant.from, price: BigNumber, }; } export const getPrice = new RestEndpoint({ path: '/price/:exchangePair', schema: ExchangePrice, });
import { useSuspense } from '@data-client/react'; import { getPrice } from './api/Price'; function PricePage() { const currentPrice = useSuspense(getPrice, { exchangePair: 'btc-usd', }); return ( <dl className="stats"> <div> <dt> {currentPrice.exchangePair.toUpperCase()}, as of{' '} <time> {currentPrice.updatedAt.toLocaleString('en-US', { dateStyle: 'medium', })} </time> </dt> <dd>${currentPrice.price.toFormat(2)}</dd> </div> </dl> ); } render(<PricePage />);
反序列化 Date
要使用传统的 Date,请把它的构造函数包装成一个函数 schema。
export class ExchangePrice extends Entity {
exchangePair = '';
updatedAt = new Date(0);
price = new BigNumber(0);
pk() {
return this.exchangePair;
}
static key = 'ExchangePrice';
static schema = {
updatedAt: iso => new Date(iso),
price: BigNumber,
};
}
缺失 Id 的情况
有些 API 的响应中不包含主键。例如,https://mystreamsite.tv/[username]/ 返回的直播中没有
username,而它是该直播唯一的标识符。
在 RestEndpoint.process() 中从 endpoint 的参数里添加 username。
{
"title": "When I'm Grandmaster, I will play faster.",
"game": "Starcraft II",
"current_viewers": 1337,
"live": true
}
class Stream extends Entity {
username = '';
title = '';
game = '';
currentViewers = 0;
live = false;
pk() {
return this.username;
}
static key = 'Stream';
}
const getStream = new RestEndpoint({
urlPrefix: 'https://mystreamsite.tv',
path: '/:username',
schema: Stream,
process(value, { username }) {
value.username = username;
return value;
},
});
行情价格
Coinbase 的行情响应中不包含主键 product_id。
RestEndpoint.process() 会从 productId 参数中添加它。
import { Entity, RestEndpoint } from '@data-client/rest'; import { Temporal } from 'temporal-polyfill'; export class Ticker extends Entity { product_id = ''; trade_id = 0; price = 0; size = '0'; time = Temporal.Instant.fromEpochMilliseconds(0); bid = '0'; ask = '0'; volume = ''; pk(): string { return this.product_id; } static key = 'Ticker'; static schema = { price: Number, time: Temporal.Instant.from, }; } export const getTicker = new RestEndpoint({ urlPrefix: 'https://api.exchange.coinbase.com', path: '/products/:productId/ticker', schema: Ticker, process(value, { productId }) { value.product_id = productId; return value; }, pollFrequency: 2000, });
嵌套对象中的键
有些 API 会把主键放在嵌套对象中,例如 { post: { id }, creator, saved }。请在 Entity.process() 中把它复制到顶层的 id,这样查找时就可以使用 { id }。示例请参阅嵌套对象中的主键。
使用 HTTP 头
要读取 HTTP Headers,请覆盖 RestEndpoint.parseResponse()。它会接收 fetch 的 Response。例如,基于游标的分页可以在响应头中发送游标。
import { RestEndpoint, RestGenerics } from '@data-client/rest';
class GithubEndpoint<
O extends RestGenerics = any,
> extends RestEndpoint<O> {
async parseResponse(response: Response) {
const results = await super.parseResponse(response);
if (
(response.headers && response.headers.has('link')) ||
Array.isArray(results)
) {
return {
link: response.headers.get('link'),
results,
};
}
return results;
}
}
文件下载
对于返回二进制数据(文件、图片、PDF)的 endpoint,请设置
content: 'blob'。其返回类型为 Blob,
schema 默认为 undefined(二进制数据无法规范化)。使用 dataExpiryLength: 0
可以避免在内存中缓存大型 blob。
import { RestEndpoint } from '@data-client/rest';
export const downloadFile = new RestEndpoint({
path: '/files/:id/download',
content: 'blob',
dataExpiryLength: 0,
});
import { useController } from '@data-client/react';
import { downloadFile } from './downloadFile';
function DownloadButton({ id }: { id: string }) {
const ctrl = useController();
const handleDownload = async () => {
const blob: Blob = await ctrl.fetch(downloadFile, { id });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'download';
a.click();
URL.revokeObjectURL(url);
};
return <button onClick={handleDownload}>Download</button>;
}
要从 Content-Disposition 头中提取文件名,请覆盖
parseResponse:
import { RestEndpoint } from '@data-client/rest';
export const downloadFile = new RestEndpoint({
path: '/files/:id/download',
content: 'blob',
dataExpiryLength: 0,
async parseResponse(response) {
const blob = await response.blob();
const disposition = response.headers.get('Content-Disposition');
const filename =
disposition?.match(/filename="?(.+?)"?$/)?.[1] ?? 'download';
return { blob, filename };
},
process(value): { blob: Blob; filename: string } {
return value;
},
});
对于 ArrayBuffer 响应(适合在内存中处理二进制数据),以同样的方式使用
content: 'arrayBuffer'。
重命名键
要重命名 API 使用的某个键,请在两个方向上映射它:Entity 的 process() 会在每个包含该 Entity 的响应中(包括列表和嵌套数据)重命名它,而 endpoint 的 getRequestInit() 会在请求体中把它改回去。这样组件就只会使用你起的名字。
import { Entity, RestEndpoint, RestGenerics } from '@data-client/rest';
export class Article extends Entity {
id = '';
carrotsUsed = 0;
static process(value: any, parent: any, key: string, args: any[]) {
const processed = super.process(value, parent, key, args);
if ('carrotsUsedIsThisNameTooLong' in processed) {
processed.carrotsUsed = processed.carrotsUsedIsThisNameTooLong;
delete processed.carrotsUsedIsThisNameTooLong;
}
return processed;
}
}
export class RenamedEndpoint<
O extends RestGenerics = any,
> extends RestEndpoint<O> {
getRequestInit(body: any) {
if (body && 'carrotsUsed' in body) {
const { carrotsUsed, ...rest } = body;
return super.getRequestInit({
...rest,
carrotsUsedIsThisNameTooLong: carrotsUsed,
});
}
return super.getRequestInit(body);
}
}
export const updateArticle = new RenamedEndpoint({
path: '/articles/:id',
method: 'PATCH',
schema: Article,
});