CDBKR

@cdbkr/react-api-core (0.0.5-dev)

Published 2026-10-14 12:33:44 +00:00 by gabriele.cerqueglini

Installation

@cdbkr:registry=https://git.codebaker.it/api/packages/CDBKR/npm/
npm install @cdbkr/react-api-core@0.0.5-dev
"@cdbkr/react-api-core": "0.0.5-dev"

About this package

Reusable API core package for React projects.

react_api_bootstrap

Reusable API bootstrap package for React projects using:

  • axios for API transport
  • @tanstack/react-query for cache and async state

Folder structure

src/
  api-response.ts
  client/
    axios-auth.ts
    axios-http-client.ts
    http-client.ts
  mappers/
    json-api-response-mapper.ts
    pagination.ts
    items-list.ts
  tanstack-query/
    api-query-shared.ts
    index.ts
    use-api-query.ts
    use-api-mutation.ts
  examples/
    ...

Import useApiQuery, useApiMutation, and ApiError from the package entry (@cdbkr/react-api-core).

Install

Create a .npmrc file in your consumer project root with:

@cdbkr:registry=https://git.codebaker.it/api/packages/CDBKR/npm/

Then install the package:

npm install @cdbkr/react-api-core

Core response model

This package models API responses as a discriminated union:

  • success response: success: true with data
  • error response: success: false with error (ErrorDetails, RFC9457-like)

Expected server formats:

{
  "success": true,
  "data": { "id": 1, "email": "user@example.com" },
  "meta": { "timestamp": "2026-03-23T12:34:56Z" }
}
{
  "success": false,
  "type": "https://example.com/probs/unauthorized",
  "title": "Unauthorized",
  "status": 401,
  "detail": "Missing or invalid token",
  "instance": "/api/v1/auth/me"
}

Axios client

import { AxiosHttpClient } from "@cdbkr/react-api-core";

const client = new AxiosHttpClient({
  baseURL: "https://api.example.com",
});

Axios client options and timeout behavior

AxiosHttpClient supports two setup modes:

  • internal Axios instance (you pass baseURL)
  • external Axios instance (you pass instance)

Default timeout behavior:

  • if the library creates Axios internally, default timeout is 30000ms
  • if you pass your own Axios instance, its own config is used (Axios default timeout is 0, no timeout, unless you set it)

Internal instance (library-managed):

const client = new AxiosHttpClient({
  baseURL: "https://api.example.com",
  // optional, defaults to 30000
  timeoutMs: 15000,
});

External instance (app-managed):

import axios from "axios";

const axiosInstance = axios.create({
  baseURL: "https://api.example.com",
  timeout: 15000, // Axios native option
});

const client = new AxiosHttpClient({
  instance: axiosInstance,
});

Important:

  • timeoutMs is used only when AxiosHttpClient creates the Axios instance internally
  • when instance is provided, configure timeout on axios.create({ timeout: ... })

Axios auth helper (interceptors)

Use configureAxiosAuth to attach auth interceptors to your Axios instance:

  • adds Authorization and optional x-api-key on requests
  • skips auth headers on public routes
  • retries once on 401 with forced token refresh
  • on refresh failure: calls onUnauthorized
  • supports authorizationPrefix (e.g. "Bearer")
  • supports onUnauthorized callback for app-level side effects
import axios from "axios";
import {
  AxiosHttpClient,
  configureAxiosAuth,
} from "@cdbkr/react-api-core";

const axiosInstance = axios.create({
  baseURL: "https://api.example.com",
});

configureAxiosAuth({
  axiosInstance,
  apiKey: "optional-api-key",
  authorizationPrefix: "Bearer",
  authProvider: {
    getToken: async (forceRefresh) =>
      forceRefresh ? await refreshToken() : await getStoredToken(),
  },
  isPublicRoute: (url) => url.pathname.startsWith("/auth/public"),
  onUnauthorized: async (_error) => {
    // e.g. clear session, redirect to login, show toast, track analytics
    await clearSession();
  },
});

const client = new AxiosHttpClient({
  baseURL: "https://api.example.com",
  instance: axiosInstance,
});

TanStack Query helpers (recommended)

import { useApiQuery } from "@cdbkr/react-api-core";
const query = useApiQuery({
  queryKey: ["me"] as const,
  request: () => client.get<unknown>("/auth/me"),
  parse: (json, meta) => {
    const source = (json ?? {}) as Record<string, unknown>;
    // meta is optional and can contain timestamp/pagination/etc.
    return { id: Number(source.id), email: String(source.email ?? "") };
  },
});

useApiQuery and useApiMutation unwrap successful responses and throw ApiError for error responses.

Mutation example:

import { useApiMutation } from "@cdbkr/react-api-core";

type UserPayload = { email: string };

const createUserMutation = useApiMutation<User, UserPayload, unknown>({
  mutationFn: (payload) => client.post<unknown>("/users", payload),
  parse: (json) => {
    const source = (json ?? {}) as Record<string, unknown>;
    return { id: Number(source.id), email: String(source.email ?? "") };
  },
});

const updateUserMutation = useApiMutation<User, UserPayload, unknown>({
  mutationFn: (payload) => client.put<unknown>("/users/me", payload),
  parse: (json) => {
    const source = (json ?? {}) as Record<string, unknown>;
    return { id: Number(source.id), email: String(source.email ?? "") };
  },
});

On backend errors (success: false), the hook throws ApiError. The RFC9457-like payload is on the instance field error (ErrorDetails | null); React Query still surfaces the thrown value as mutation.error.

Optional parse for no-data endpoints

parse is optional when you just need the raw success payload (TRaw | null), for example in DELETE or export endpoints.

const deleteUserMutation = useApiMutation({
  mutationFn: (userId: number) => client.delete<unknown>(`/users/${userId}`),
});
const exportReportQuery = useApiQuery({
  queryKey: ["reports", "export"] as const,
  request: () => client.get<unknown>("/reports/export"),
});

In these cases, data is null when backend responds with:

  • { "success": true }
  • { "success": true, "data": null }
  • 204 No Content

If you need a mapped domain type, keep using parse (recommended for regular CRUD reads/writes).

Note: when omitting parse, do not force the 3 generic parameters (<TData, TVariables, TRaw>), otherwise TypeScript selects the overload where parse is required.

List utilities (optional pagination)

import {
  listFromJson,
  paginationFromMeta,
  type ItemsList,
} from "@cdbkr/react-api-core";

Use these utilities when your API returns list payloads in data. If pagination is present in meta, it is mapped as optional pagination.

itemsKey is the array key inside data (default: "items").

Example backend shape:

{
  "success": true,
  "data": {
    "items": [{ "id": 1, "email": "a@x.com" }]
  },
  "meta": {
    "pagination": {
      "page": 1,
      "perPage": 20,
      "total": 100,
      "totalPages": 5
    }
  }
}

Example query parser:

type UsersList = ItemsList<User>;

const usersQuery = useApiQuery({
  queryKey: ["users"] as const,
  request: () => client.get<unknown>("/users"),
  parse: (json, meta): UsersList =>
    listFromJson<User>(json, userFromJson, {
      itemsKey: "items", // name of array inside data
      meta,
      paginationFromMeta,
    }),
});

Mapper usage (manual)

If you need to map raw API responses outside TanStack Query:

import { mapJsonApiResponse } from "@cdbkr/react-api-core";

const raw = await client.get<unknown>("/auth/me");
const mapped = mapJsonApiResponse(raw, (json) => {
  const source = (json ?? {}) as Record<string, unknown>;
  return { id: Number(source.id), email: String(source.email ?? "") };
});

Example

A complete usage example with a React component is available in:

  • src/examples/react-usage-example.tsx

OpenAPI client generator (react-gen)

This library ships a small wrapper around openapi-generator-cli to generate TypeScript client + Zod schemas.

The goal is: the consuming app only needs to provide openapi.json in a known place, and optionally select which models to generate.

Defaults

When you run react-gen, it assumes:

  • OpenAPI input spec: ./openapi.json (project root)
  • Output directory: ./src/generated/openapi-zod

Model selection

You can generate only specific models via --models.

Syntax:

  • model list separated by : (colon), e.g. User:BillingOrder:OrderStatus
  • example: --models BillingOrder:OrderStatus:User

If you omit --models, the generator will attempt to generate all models.

When --models is provided, react-gen automatically keeps transitive model dependencies required by the selected models (based on generated model imports), so the output remains compilable.

At the end of generation, it prints a summary with:

  • requested models
  • auto-included dependencies
  • models not found in the spec (if any)

Cleaning output

Add --clean to remove the output directory before generating (recommended to avoid stale generated files).

Custom input/output (optional)

You can override defaults with:

  • --input <path-to-openapi.json>
  • --output <output-directory>

Examples

Generate everything (with clean):

npx react-gen --clean

Generate only selected models:

npx react-gen --models BillingOrder:OrderStatus:User --clean

Generate with custom paths:

npx react-gen --input ./openapi-generated/openapi.json --output ./src/generated/openapi-zod --models User --clean

Publish

Available commands:

Command Description
npm run release Full publish flow (build → auth → publish)
npm run release:dry Dry run — all checks and version logic, no publish
npm run unpublish Unpublish the entire package from the registry

Or run the script directly:

bash scripts/publish.sh           # full publish
bash scripts/publish.sh --dry-run # dry run

Version convention

package.json always holds a clean base semver (e.g. 0.0.3). The prerelease suffix (-dev.N) only appears in the published registry version — never in package.json. The script enforces this and warns if it detects a prerelease version in package.json.

What the script does

  1. Detects branch — determines mode automatically:

    • main / master → prod (npm tag: latest)
    • any other branch → dev (npm tag: dev)
  2. Checks the registry — queries the gitHead for the relevant tag. Warns if the remote is already at the same commit.

  3. Validates package.json — if a prerelease version is found, the script stops and asks to strip it back to the clean base.

  4. Computes the next version from the registry (source of truth):

    • dev: increments the prerelease counter from the last published dev version (e.g. 0.0.3-dev.2 → 0.0.3-dev.3); if the base semver in package.json changed, starts a new series (0.0.4-dev.0)
    • prod: prompts for patch / minor / major, computes from the last published prod version
    • If package.json differs from the auto-computed version, warns and asks whether to restore the automatic bump
  5. Runs npm run build before publishing.

  6. Authenticates — asks for username and password, obtains a temporary auth token from the Verdaccio API. The token is injected into .npmrc only for the duration of the script and removed on exit (even on errors).

  7. Publishes to the private registry with the correct tag.

    • Dev: package.json is temporarily set to the dev version for publish, then restored to the clean base semver automatically.
    • Prod: package.json is updated to the new release version permanently.
  8. Git commit + tag (prod only) — optionally creates a build: bump version to x.y.z commit and a vx.y.z tag. You still need to push manually:

git push && git push --tags

Dev versions

Dev publishes produce pre-release versions with the dev tag:

npm install @cdbkr/react-api-core@dev

Prod versions

Prod publishes update the latest tag:

npm install @cdbkr/react-api-core
# or explicitly:
npm install @cdbkr/react-api-core@latest

Dependencies

Dependencies

ID Version
axios ^1.13.0
zod ^4.3.6

Development Dependencies

ID Version
@tanstack/react-query ^5.90.5
tsup ^8.5.1
typescript ^5.9.3

Peer Dependencies

ID Version
@tanstack/react-query ^5.90.5

Keywords

api react typescript axios tanstack-query
Details
npm
2026-10-14 12:33:44 +00:00
38
ISC
dev
22 KiB
Assets (1)
Versions (1) View all
0.0.5-dev 2026-10-14