Skip to content

Runnable HTTP example

This repository example has no external network dependency. The fixture returns { "id": 1, "name": "Ada" } for GET /users/1 and a JSON 404 for every other request.

Server

mjs
/*
 * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { createServer } from 'node:http';

const server = createServer((request, response) => {
  const found = request.method === 'GET' && request.url === '/users/1';
  response.writeHead(found ? 200 : 404, {
    'content-type': 'application/json; charset=utf-8',
  });
  response.end(
    JSON.stringify(found ? { id: 1, name: 'Ada' } : { error: 'Not Found' }),
  );
});

server.listen(8787, '127.0.0.1', () => {
  console.log('Fixture listening on http://127.0.0.1:8787');
});

process.on('SIGINT', () => server.close());

Client

ts
/*
 * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {
  ExchangeError,
  Fetcher,
  HttpStatusValidationError,
  ResultExtractors,
} from '@ahoo-wang/fetcher';

interface User {
  id: number;
  name: string;
}

const client = new Fetcher({ baseURL: 'http://127.0.0.1:8787' });
const user = await client.get<User>(
  '/users/1',
  {},
  { resultExtractor: ResultExtractors.Json },
);

if (user.id !== 1 || user.name !== 'Ada') {
  throw new Error(`Unexpected user: ${JSON.stringify(user)}`);
}

try {
  await client.get('/missing');
  throw new Error('Expected /missing to fail with HTTP 404');
} catch (error) {
  if (
    !(error instanceof ExchangeError) ||
    !(error.cause instanceof HttpStatusValidationError) ||
    error.exchange.response?.status !== 404
  ) {
    throw error;
  }
}

console.log(user.name);

The client selects JSON extraction in the third argument to get. It also confirms that /missing becomes an ExchangeError whose cause is HttpStatusValidationError and whose response status is 404; any other error is rethrown.

Run in this repository

From the repository root, use the repository's Node >=20.20.2 and pnpm 10.34.5 toolchain:

bash
pnpm --filter @ahoo-wang/fetcher build
pnpm exec tsc -p wiki/examples/http/tsconfig.json
node wiki/examples/http/server.mjs

Keep that terminal open. In another terminal, run:

bash
node wiki/examples/http/dist/client.js

Expected output:

text
Ada

Press Ctrl+C in the server terminal to stop the fixture. See Your first request to copy this example into an independent project.

Released under the Apache License 2.0.