The problem
Take the back office of an online shop: a Vue front,
fronts/admin, that consumes the APIs of the
order, stock and
shipping services. A TypeScript SDK is
generated from each API's OpenAPI spec, and the screens call
it with a useQuery written on the spot.
Every screen depends on the API contract.
The templates read status, dates arrive as
strings, null and undefined get
mixed up. Rename one field, and the regenerated SDK breaks
screens scattered across the front.
Cache keys are written by hand. One screen
reads ['order', id], another
['orders', id]. After a shipment, the
invalidation misses half of them, and a list shows a stale
state.
Every screen does it its own way. One subscribes to the Mercure hub in the view, another polls the API at regular intervals. A coding agent adding a screen imitates the nearest one, and the sprawl grows.
The options
Calling the generated SDK from the components
- What it solves: no layer to write, and the SDK's typing follows the API.
-
What it costs: the symptoms above. The
API's representation (JSON-LD, names,
null) enters the cache and the templates.
One Pinia store per resource
- What it solves: a single access point per resource, shared by the screens.
- What it costs: Pinia manages client state, not server state. Caching, deduplication, refetching and loading states have to be rewritten in each store, while TanStack Query provides them.
One generic composable per resource
-
What it solves: few files. A
useResource('orders')exposes read, list, create and update. - What it costs: workflow transitions and business actions do not fit this CRUD. The typing turns generic, and so does the mapping: a spread of the response, or nothing.
One composable per endpoint, with its explicit mappers
- What it solves: each endpoint (read, list page, write, transition) has its folder, always the same. The screens only see the front's model.
- What it costs: more files, and repetitive code from one folder to the next.
Our recommendation
One folder per endpoint, always the same: a TanStack Query composable and its explicit mappers. The screens only import these composables and the front's business model.
The composable owns the URL and the mappers; its caller sets the rest (key, options, callbacks). The business model belongs to the front: it follows no API representation.
A model with optional fields
No endpoint gives every field of an order: the list gives fewer than the detail. Every field of the model is therefore optional, and one utility states what each side guarantees or requires:
// libs/typescript/front-model/WithRequired.ts
/** A concept with these fields guaranteed. */
export type WithRequired<T, K extends keyof T> = T & Required<Pick<T, K>>;
Where a page passes an endpoint's data to a component,
vue-tsc checks that the one covers the other. A
component that requires customerId accepts the
data of get-order, not that of
list-orders.
What this shape gives a coding agent
Adding cancel-order comes down to copying
ship-order, then renaming. The typing checks
the copy at both ends: mapToModel reads the
SDK's typed response, mapToRequest produces its
typed request. A forgotten required field, or a misnamed
one, fails at compile time, not in production.
A coding agent, like a new developer, looks for an example to imitate. When every folder looks alike, the nearest example is the right one, and its copy can be checked. The rule fits in one sentence, and the linter enforces it.
The trade-offs we accept
More files. Two to four per endpoint, even for a delete. Each file has a single role, and its name says which.
Repetitive code, on purpose. The
mapToModel of get-order and that
of ship-order list almost the same fields. We
do not factor them out: each endpoint has its own response
type, and a shared mapper would hide the day they diverge.
No generator and no tests at first. We settle the structure first, on a few resources. A generator would freeze a shape that still moves; the mapper tests will come next.
One GET per item when the API cannot filter by
id.
For a "watched orders" screen,
useGetEachOrder(ids) runs a
useQueries under the
detail(id) keys. It shares the cache of
useGetOrder, at the cost of one request per
order.
The signal that should make us revisit this choice: folders that drift apart, or copies that forget the cache upkeep. That is the time to write the generator and the tests. If per-item GETs multiply, the API deserves a filter by id.
Implementation
The examples use Vue 3.5, TanStack Query 5
(@tanstack/vue-query) and an SDK generated by
hey-api. The order service exposes its
DTO resources
with API Platform.
1. The tree
libs/
typescript/
front-model/ # the front's business model, framework-free
WithRequired.ts
order/Order.ts
api-mapping/ # optional, required, toDate, oneOf, toCollection
order-api-sdk/ # generated, never edited by hand
vue/
api-query/ # createResourceQueryKeys, ApiQueryOptions, useMercure
order-api/
client/orderApiClient.ts
endpoint/orders/
queryKeys.ts
get-order/
useGetOrder.ts
mapToModel.ts
index.ts
list-orders/
useListOrders.ts
mapToModel.ts
index.ts
ship-order/
useShipOrder.ts
mapToModel.ts
mapToRequest.ts
index.ts
One Vue lib per API, a single business model for all of
them. A folder's index.ts only exports the
composable and its types. The client holds the service's URL
and the user's token.
The name follows the operation at every layer. On the API
side, we set the operationId (openapi: new Model\Operation(operationId:
'shipOrder')). The SDK then exposes shipOrder(),
ShipOrderData and
ShipOrderResponse, and the folder is named
ship-order.
2. The front's model
// libs/typescript/front-model/order/Order.ts
/** Where an order stands in its workflow. */
export const ORDER_STATE = {
Draft: 'draft',
Placed: 'placed',
Paid: 'paid',
Shipped: 'shipped',
Cancelled: 'cancelled',
} as const;
export type OrderState = (typeof ORDER_STATE)[keyof typeof ORDER_STATE];
/** An order as the front sees it: every field is optional. */
export interface Order {
id?: string;
reference?: string;
/** Undefined for a state this front does not know yet. */
state?: OrderState;
customerId?: string;
carrier?: string;
trackingNumber?: string;
placedAt?: Date;
}
/** What the shipping form gives. */
export interface OrderShipInput {
carrier: NonNullable<Order['carrier']>;
trackingNumber: NonNullable<Order['trackingNumber']>;
}
A concept is identified by id, whatever the API
calls it. Its position in a workflow is called
state for every API, whether they say
status or place. An input types
its fields from the concept.
3. The mapper, field by field
// libs/vue/order-api/endpoint/orders/get-order/mapToModel.ts
import type { GetOrderResponse } from '@app/order-api-sdk';
import { oneOf, optional, required, toDate } from '@app/api-mapping';
import { ORDER_STATE, type Order } from '@app/front-model/order/Order';
import type { WithRequired } from '@app/front-model/WithRequired';
/** The fields this endpoint always gives. */
export type Model = WithRequired<Order, 'id' | 'reference' | 'customerId'>;
/** The order this endpoint returns, and the hub pushes, as the front's model. */
export function mapToModel(data: GetOrderResponse): Model {
return {
id: required(data.id, 'order id'),
reference: required(data.reference, 'order reference'),
// The API calls the workflow position status: the front only knows state.
state: oneOf(ORDER_STATE, data.status),
customerId: required(data.customerId, 'order customerId'),
carrier: optional(data.carrier),
trackingNumber: optional(data.trackingNumber),
placedAt: toDate(data.placedAt),
};
}
Never a spread: ...data would bring the JSON-LD
fields (@id, @type) into the
model, along with every field the API adds. Field by field,
a rename in the spec breaks this mapper at compile time, not
the screens.
The api-mapping helpers stay small:
optional (null becomes
undefined), required (a missing
value throws), toDate.
oneOf returns undefined for an
unknown state. toCollection maps a Hydra page
(member, totalItems,
view) for list-orders, whose
Member type is narrower.
4. The query keys
// libs/vue/order-api/endpoint/orders/queryKeys.ts
import type { ListOrdersData } from '@app/order-api-sdk';
import { createResourceQueryKeys } from '@app/vue-api-query';
export const orderKeys = createResourceQueryKeys<ListOrdersData['query']>('order', 'orders');
The factory returns keys from the widest to the narrowest:
all, lists(),
list(filters), details(),
detail(id). TanStack Query invalidates by
prefix: orderKeys.lists() covers every page,
whatever its filters. The API's name comes first, so that
two APIs never collide in the cache.
A list's filters keep the SDK's type
(ListOrdersData['query']). The screen passes an
object literal that TypeScript checks, without importing
anything from the SDK.
5. The read composable
// libs/vue/order-api/endpoint/orders/get-order/useGetOrder.ts
import { getOrder, type GetOrderResponse } from '@app/order-api-sdk';
import { useMercure, type ApiQueryOptions } from '@app/vue-api-query';
import { useQuery, useQueryClient } from '@tanstack/vue-query';
import { computed, toValue, type MaybeRefOrGetter } from 'vue';
import { orderApiClient } from '../../../client/orderApiClient';
import { orderKeys } from '../queryKeys';
import { mapToModel, type Model } from './mapToModel';
/** One order, GET /orders/{id}. live: kept up to date by the Mercure hub. */
export function useGetOrder(
id: MaybeRefOrGetter<string | undefined>,
options: ApiQueryOptions<Model> & { live?: boolean } = {},
) {
const { enabled = true, live = false, ...queryOptions } = options;
const query = useQuery({
queryKey: computed(() => orderKeys.detail(toValue(id) ?? '')),
...queryOptions,
// The caller's enabled adds to what the composable waits for: an id.
enabled: () => Boolean(toValue(id)) && toValue(enabled),
async queryFn() {
const { data } = await getOrder({
client: orderApiClient,
path: { id: toValue(id) ?? '' },
throwOnError: true,
});
return mapToModel(data);
},
});
if (live) {
const queryClient = useQueryClient();
useMercure(
() => (toValue(id) ? [`https://example.com/orders/${toValue(id)}`] : []),
(payload: GetOrderResponse) => {
// Same representation as the GET: same mapper, no round trip.
const order = mapToModel(payload);
queryClient.setQueryData(orderKeys.detail(order.id), order);
},
);
}
return query;
}
ApiQueryOptions<Model> carries every
useQuery option but queryFn. With
throwOnError: true, the SDK rejects its promise
on an HTTP error. For prefetching, the folder may also
export a queryOptions() that the composable
reuses.
useMercure opens an EventSource on
the Mercure hub. If the service publishes a representation
other than the GET's, the composable invalidates the key
instead. useListOrders, for its part,
invalidates orderKeys.lists() on every update.
6. A transition, and the invalidation
// libs/vue/order-api/endpoint/orders/ship-order/mapToRequest.ts
import type { ShipOrderData } from '@app/order-api-sdk';
import type { OrderShipInput } from '@app/front-model/order/Order';
export interface ShipOrderVariables {
id: string;
input: OrderShipInput;
}
/** The transition's request, from what the form gives. */
export function mapToRequest({ id, input }: ShipOrderVariables): Omit<ShipOrderData, 'url'> {
return {
path: { id },
body: {
carrier: input.carrier,
trackingNumber: input.trackingNumber,
},
};
}
// libs/vue/order-api/endpoint/orders/ship-order/useShipOrder.ts
import { shipOrder } from '@app/order-api-sdk';
import type { ApiMutationOptions } from '@app/vue-api-query';
import { useMutation, useQueryClient } from '@tanstack/vue-query';
import { orderApiClient } from '../../../client/orderApiClient';
import { orderKeys } from '../queryKeys';
import { mapToModel, type Model } from './mapToModel';
import { mapToRequest, type ShipOrderVariables } from './mapToRequest';
/** The ship transition, PATCH /orders/{id}/ship. Then refetches the order and the lists. */
export function useShipOrder(options: ApiMutationOptions<Model, ShipOrderVariables> = {}) {
const queryClient = useQueryClient();
return useMutation({
onSuccess: (_order, { id }) =>
Promise.all([
queryClient.invalidateQueries({ queryKey: orderKeys.detail(id) }),
queryClient.invalidateQueries({ queryKey: orderKeys.lists() }),
]),
...options,
async mutationFn(variables: ShipOrderVariables) {
const { data } = await shipOrder({
client: orderApiClient,
...mapToRequest(variables),
throwOnError: true,
});
return mapToModel(data);
},
});
}
The cache upkeep is the default onSuccess. It
returns its promise: the mutation stays pending until the
refetches are done. A transition that touches other
resources adds their keys here.
A screen that wants to react to the success passes its
callback to mutate(variables, { onSuccess }).
TanStack Query calls it after the composable's, which keeps
the cache upkeep. An onSuccess passed in the
options, on the other hand, would replace that upkeep.
7. The screen only knows the model
<!-- fronts/admin/src/pages/order/PageOrder.vue -->
<template>
<OrderCustomerCard
v-if="order"
:order="order"
/>
<ShipOrderForm @submit="(input) => ship({ id: orderId, input })" />
</template>
<script setup lang="ts">
import { useGetOrder } from '@app/vue-order-api/endpoint/orders/get-order';
import { useShipOrder } from '@app/vue-order-api/endpoint/orders/ship-order';
import OrderCustomerCard from '@/components/OrderCustomerCard.vue';
import ShipOrderForm from '@/components/ShipOrderForm.vue';
const props = defineProps<{ orderId: string }>();
const { data: order } = useGetOrder(() => props.orderId, { live: true });
const { mutate: ship } = useShipOrder();
</script>
OrderCustomerCard declares
order: WithRequired<Order, 'reference' |
'customerId'>. vue-tsc checks this type against the
Model of get-order, and the screen
imports nothing from the SDK.
8. The boundary, checked by the linter
// eslint.config.js (excerpt)
export default [
{
files: ['fronts/*/src/**/*.{ts,vue}'],
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
{
regex: '^@app/[a-z-]+-api-sdk(/|$)',
message: 'Screens use an endpoint composable of libs/vue/<api>-api, never the SDK.',
},
{
regex: '^@app/vue-[a-z-]+-api/client(/|$)',
message: 'The API client is reserved for its endpoint composables.',
},
],
},
],
},
},
];
The rule also refuses import type (allowTypeImports
defaults to false): a screen types nothing with
the SDK. With eslint-plugin-vue, it covers the
<script> of single-file components. A
grep on @app/[a-z-]+-api-sdk in CI
backs the rule up at little cost.
Checklist
- One folder per endpoint, named after its operation, with its composable and its mappers.
- Mappers that list every field, without a spread.
-
A front business model with optional fields, identified by
id, withstatefor a workflow. -
Endpoints and components that declare their fields with
WithRequired. - Query keys from a single factory, the API's name first.
-
A mutation that refetches by default what it makes stale;
a screen's callbacks passed to
mutate(). -
No import of the SDK or the client outside the API libs,
checked by
no-restricted-imports. -
vue-tscin CI, to check the props in the templates.
Sources
Versions checked on 15 November 2026:
@tanstack/vue-query 5.107.1, Vue 3.5.45,
@hey-api/openapi-ts 0.99.0, ESLint 10.15.0, API
Platform 5.0.7.
- TanStack Query (Vue), Query Keys, Reactivity and Query Invalidation: keys, reactive getters, invalidation by prefix.
-
TanStack Query (Vue),
Mutations
and
Invalidations from Mutations:
mutate()callbacks, the promise ofonSuccess. -
TanStack Query (Vue),
Query Options,
Parallel Queries
and
client state:
queryOptions,useQueries, server state. -
Vue,
Using Vue with TypeScript:
vue-tsc. -
hey-api,
SDK,
TypeScript
and
Migrating: one function per operation, the
clientoption,DataandResponsetypes,throwOnError. -
ESLint,
no-restricted-imports:
patterns,regex,allowTypeImports. -
API Platform,
OpenAPI
and
the Model\Operation class: an operation's
operationId. - Lychen, pull requests 260, 262, 263 and 267: an open-source implementation of what this article describes, across three APIs, in a moon monorepo.
- Lychen, pull request 256: screens wired to these composables, with no SDK import.