
# TypeScript {/* #typescript */}

Bắt đầu với [hướng dẫn gRPC](/docs/vi/api/grpc) để tạo token API và tải `platform.proto`. Chạy lệnh sau trong thư mục chứa tệp đó.

Trình duyệt không mở được kết nối gRPC HTTP/2 gốc. API nền tảng cũng nhận [gRPC-Web](https://github.com/grpc/grpc-web) trên HTTP/1.1. Cài `protoc`, plugin `protoc-gen-js`, `protoc-gen-grpc-web` và các gói runtime:

```bash
npm install grpc-web google-protobuf
npm install --save-dev @types/google-protobuf
mkdir -p src/generated
protoc -I. platform.proto \
  --js_out=import_style=commonjs,binary:src/generated \
  --grpc-web_out=import_style=typescript,mode=grpcweb:src/generated
```

Tải plugin biên dịch từ [bản phát hành và hướng dẫn gRPC-Web chính thức](https://github.com/grpc/grpc-web#code-generator-plugins); phải có trong `PATH`. Lệnh tạo `platform_pb.js`, khai báo TypeScript và `PlatformServiceClientPb.ts`.

```typescript
import {PlatformServicePromiseClient} from './generated/PlatformServiceClientPb';
import {GetCatalogRequest, ListCatalogsRequest} from './generated/platform_pb';

// Supply a token at runtime. Do not bundle a long-lived API token in browser code.
export async function listCatalogDetails(token: string) {
  const client = new PlatformServicePromiseClient('https://reconstruct.dev');
  const metadata = {authorization: `Bearer ${token}`};
  const listRequest = new ListCatalogsRequest();
  listRequest.setPageSize(10);

  const page = await client.listCatalogs(listRequest, metadata);
  for (const catalog of page.getCatalogsList()) {
    const detailRequest = new GetCatalogRequest();
    detailRequest.setCatalogId(catalog.getCatalogId());
    const detail = await client.getCatalog(detailRequest, metadata);
    console.log(detail.getCatalogId(), detail.getDescription());
  }
}
```

Với ứng dụng trình duyệt, API công khai phải cho phép origin của ứng dụng qua CORS. Giữ token lâu dài trên máy chủ tin cậy; bundle trình duyệt không bảo vệ được bí mật nhúng.
