Skip to content

Vue Mixins — API Reference ​

ts
import { ... } from '@dynamicforms/fastapi-viewsets';

Each mixin is an interface merged with a class of the same name. The interface names the actions and their signatures; the class carries static readonly actions, the same statement in a form that survives to runtime. A ViewSet declaration lists the mixin classes themselves: the list types the ViewSet's public surface, and is what the schema check compares against the BE.

The members are methods, not function-valued properties, so a ViewSet may override an action with a method of its own. An action returns a ViewSetActionCall<R>: a Promise<R> whose key is optional in the type, so an override may return a plain Promise<R>.

Types ​

ts
type KeyType = string | number;
type DestroyReturnData<K extends KeyType = KeyType> = Record<K, null>;
type BulkDestroyReturnData<K extends KeyType = KeyType> = Record<K, ApiErrorBody | null>;

interface LookupItem {
  group: unknown;
  pk: unknown;
  title: string;
  icon: string | null;
}

/** `q` and `ids` of the BE default `LookupFilter`, and the other fields of the BE lookup filter model. */
interface LookupParams {
  q?: string;
  ids?: Array<string | number>;
  [key: string]: string | number | boolean | null | undefined | Array<string | number>;
}

/**
 * `sort` is 'column:asc,other:desc'; the rest are filters. Without `sort` the BE applies its
 * `default_sort`; '' leaves the list unordered.
 */
interface ListParams {
  sort?: string;
  [key: string]: string | number | boolean | null | undefined | Array<string | number>;
}

/** The shape of `@dynamicforms/vue-grid`'s `SortStateColumn`: a `SortState` is a grid's `sortState`. */
interface SortStateColumn {
  columnName: string;
  direction: 'asc' | 'desc';
}
type SortState = SortStateColumn[];

interface PageParams extends ListParams {
  offset?: number;
  limit?: number;
}

interface PaginatedList<T> {
  results: T[];
  offset: number;
  limit: number | null;
  count: number | null;
  hasMore: boolean;
  hasPrevious: boolean;
}

interface CursorParams extends ListParams {
  cursor?: string;
  limit?: number;
}

interface CursorPage<T> {
  results: T[];
  limit: number;
  hasMore: boolean;
  hasPrevious: boolean;
  next: string | null;
  previous: string | null;
  first: string | null;
  last: string | null;
}

Requests and actions ​

ts
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';

/** Query values; an array becomes a repeated key, which is how FastAPI binds `list[str]`. */
type QueryParams = Record<string, string | number | boolean | null | undefined | Array<string | number>>;

interface RequestOptions {
  query?: QueryParams;
  /** JSON, or a FormData sent as multipart/form-data as it is (REST only). */
  body?: unknown;
  /** Headers for this call only; on muxws they override the proxy's own `headers`. */
  headers?: Record<string, string>;
  /** The Idempotency-Key of this call; a new UUID when absent. Overrides an Idempotency-Key in `headers`. */
  key?: string;
  /** Overrides the proxy's `repeat` for this call. */
  repeat?: RepeatOptions;
  /** Reported to `onCallActivity` listeners as `background: true`; default false. See also `inBackground`. */
  background?: boolean;
  /** REST only. Called as the request body is sent; a repeated attempt reports from 0 again. */
  onUploadProgress?: (loaded: number, total: number | undefined) => void;
  /** Default 'json'. With 'blob' (REST only) the call resolves to a FileDownload. */
  responseType?: 'json' | 'blob';
}

/** The options of a call that answers with a file. */
type BlobRequestOptions = RequestOptions & { responseType: 'blob' };

/** The response shapes of `GET {basePath}`, as the BE names them in `X-List-Shape`. */
type ListShape = 'plain' | 'paginated' | 'cursor';

/** One entry of a ViewSet's `declares`: a mixin naming the actions it contributes. */
interface ViewSetMixinDeclaration {
  readonly actions: readonly string[];
}

/** Every action a mixin can name: 'list', 'listPage', 'listCursor', 'create', 'retrieve', ... */
type ActionName = keyof ActionSurface<KeyType, unknown, never, string>;

/** The members of the mixins whose actions are in `A`, intersected: the public surface of a factory-built ViewSet. */
type ActionSurface<K extends KeyType, T, PK extends keyof T, A, L = LookupItem> = ('create' extends A
  ? CreateMixin<T, PK>
  : unknown) &
  ('bulkCreate' extends A ? BulkOnlyCreateMixin<T, PK> : unknown) &
  ('list' extends A ? ListMixin<T> : unknown) &
  ('listPage' extends A ? PaginatedListMixin<T> : unknown) &
  ('listCursor' extends A ? CursorListMixin<T> : unknown) &
  ('retrieve' extends A ? RetrieveMixin<K, T> : unknown) &
  ('update' extends A ? UpdateMixin<K, T> : unknown) &
  ('bulkUpdate' extends A ? BulkOnlyUpdateMixin<K, T> : unknown) &
  ('destroy' extends A ? DestroyMixin<K> : unknown) &
  ('bulkDestroy' extends A ? BulkOnlyDestroyMixin<K> : unknown) &
  ('lookup' extends A ? LookupMixin<L> : unknown);

request<R>(method: HttpMethod, path: string, options?: RequestOptions): ViewSetCall<R> is the one call a transport implements; see custom endpoints. An overload types a call with responseType: 'blob' as ViewSetCall<FileDownload>. The muxws transport rejects a call with a FormData body, onUploadProgress or responseType: 'blob' with an Error naming the option. ViewSetCall, ViewSetActionCall and RepeatOptions are in Idempotency.

FileDownload ​

ts
/** The answer of a call made with `responseType: 'blob'`. */
interface FileDownload {
  /** The response body; its `type` is `contentType`. */
  blob: Blob;
  /** From Content-Disposition: `filename*` (RFC 5987) when present, else `filename`, else null. */
  filename: string | null;
  /** The Content-Type header; '' when there is none. */
  contentType: string;
  /** The response headers, names in lower case. */
  headers: Record<string, string>;
}

/** The file name in a Content-Disposition value: `filename*` before `filename`; null when it has neither. */
function contentDispositionFilename(header: string | null | undefined): string | null;

filename* is decoded by its charset (UTF-8''track-1-%C3%A9.pdf is track-1-é.pdf); filename is taken quoted or as a token. See Files.

watch() ​

Every ViewSet has watch(), whichever mixins it declares: a factory-built one, a route_rest or route_muxws proxy, and a class extending RestProxyImpl or MuxwsProxyImpl. The type of a route_rest proxy built from positional arguments, which take no events, carries no watch().

ts
interface ViewSetWatch<T, K extends KeyType = KeyType> {
  watch<Row>(options: Omit<WatchOptions<NoInfer<Row>, K>, 'fetch'> & { fetch: FetchRows<Row, K> }): EventSubscription;
  watch(options: WatchOptions<T, K>): EventSubscription;
}

type FetchRows<T, K extends KeyType = KeyType> = (pks: K[]) => Promise<readonly T[]>;

interface WatchOptions<T, K extends KeyType = KeyType> {
  onChange: (change: RecordsChanged<T, K>, meta: EventMeta) => void;
  onResync: () => void;
  fetch?: boolean | FetchRows<T, K>;
  onError?: (error: unknown) => void;
  topic?: string;
}

/** The record type a mixin interface `M` names, read off its actions; `Record<string, unknown>` for none. */
type RecordOf<M> = M extends { retrieve(...args: any[]): Promise<infer T> }
  ? T
  : M extends { list(...args: any[]): Promise<(infer T)[]> }
    ? T
    : M extends { create(...args: any[]): Promise<infer T> }
      ? T
      : M extends { listPage(...args: any[]): Promise<PaginatedList<infer T>> }
        ? T
        : M extends { listCursor(...args: any[]): Promise<CursorPage<infer T>> }
          ? T
          : Record<string, unknown>;

/** The pk type a mixin interface `M` names, read off its actions; `KeyType` for none. */
type KeyOf<M> = M extends { retrieve(pk: infer K): any }
  ? K & KeyType
  : M extends { destroy(pk: infer K): any }
    ? K & KeyType
    : M extends { update(pk: infer K, ...args: any[]): any }
      ? K & KeyType
      : KeyType;

watch(options) subscribes the ViewSet's topic, options.topic, else the ViewSet's topic option, else its basePath, to records_changed (RECORDS_CHANGED) and returns the EventSubscription. The event client is events from the ViewSet's options; without it, a muxws ViewSet uses eventsOf(peer), and a REST ViewSet throws.

OptionMeaning
onChangeRequired. Called once per records_changed event of version 1 of the topic (with fetch, twice for an event some of whose records are gone), with its RecordsChanged payload and its EventMeta
onResyncRequired. Called on a resync of the topic, and for a records_changed event whose version is not 1, with or without fetch: the caller re-reads what it displays
fetchtrue: every created and updated change without record is completed with retrieve(pk), issued inside inBackground so call activity reports it as a background call, before onChange, and the changes whose retrieve answers 404 follow the event in a second onChange with op: 'deleted' and the same meta; when every retrieve answers 404 only that one is called. A retrieve that fails with another error is passed to onError and the event ends in onResync instead of onChange. A FetchRows function: called once per created or updated event with the pks of its changes without record, inside inBackground; its rows are matched to the changes by the ViewSet's pkFieldName, and a pk without a row follows in the deleted onChange as a 404 does; a rejection is passed to onError and the event ends in onResync. With a function, onChange receives the rows it returns, whatever their type. Default false
onErrorCalled with the error of a refused subscribe or poll of the topic, of a failed fetch retrieve, and of a rejected fetch function
topicThe client topic to subscribe: the BE path relative to the application's root_path, without a Starlette Mount prefix. Default the ViewSet's topic option, else its basePath

onChange and onResync are called in the order their events arrived, also while fetch waits for a retrieve. With fetch, onChange is called for an event whose changes were all dropped, with an empty changes. After unsubscribe() of the returned subscription no option is called, also for an event that arrived before it and whose retrieve is still in flight.

The callbacks are function-typed properties: a callback whose parameter is typed other than the option's, a wider record type included, does not compile. An onChange that declares only the change parameter compiles.

Throws ErrorWhen
[ViewSet {basePath}] watch() needs an event client: pass `events` in the ViewSet's optionsA REST ViewSet without events
[ViewSet {basePath}] watch() found no event client for the peer: createEventClient({ peer }) registers oneA muxws ViewSet without events whose peer has no client. Before a function peer has resolved, watch() returns, and once the peer resolves ready rejects with the error and onError is called with it; without onError it is rethrown in a microtask

RestProxy<M> and MuxwsProxy<M> carry watch() as ViewSetWatch<RecordOf<M>, KeyOf<M>>, a factory-built ViewSet as ViewSetWatch<T, PkType<T, PK>> (PkType). Applying the changes to a list of rows is applyChanges; the guide is watch() on a ViewSet.

Errors ​

ts
class ViewSetRequestError extends Error {
  readonly response: { status: number; data: unknown; headers: Record<string, string> };

  constructor(status: number, data: unknown, headers?: Record<string, string>);
}

headers are the reply headers with the :-prefixed pseudo-headers dropped and every value stringified, {} when the constructor is not given any. name is 'ViewSetRequestError' and the message is Request failed with status code {status}.

ts
class ListShapeMismatchError extends Error {
  readonly expected: ListShape;
  readonly received: ListShape | 'unknown';
}

Thrown by list(), listPage() and listCursor() when the reply is not the envelope the method requested: plain is an array, paginated an object with results and offset, cursor an object with results, next and has_more. received is 'unknown' for a body that matches none of them. name is 'ListShapeMismatchError' and the message is Expected a '{expected}' list from the BE, received '{received}'.

Which transport throws ViewSetRequestError and which throws axios' own AxiosError, and what a handler may read off either, is in handling a failed call.

Error bodies ​

ts
/** The body of every error response of the BE. */
interface ApiErrorBody {
  detail: string;
  detail_code: string;
  detail_params: Record<string, unknown>;
  field_errors: Record<string, ApiFieldError[]>;
}

/** One failure of one field of a request that failed validation. */
interface ApiFieldError {
  code: string; // a FieldErrorCode, pydantic.<type>, django.<code>, an application code or pydantic.custom_error
  params: Record<string, unknown>;
  detail: string;
}

/** The params of each field error code the BE declares; see Field error codes. */
interface FieldErrorParams {
  'fastapi-viewsets.required': Record<string, never>;
  'fastapi-viewsets.min_length': { minLength: number };
  // ... one entry per code
  'fastapi-viewsets.unique': { fields: string[] };
}
type FieldErrorCode = keyof FieldErrorParams;
interface FieldErrorOf<C extends FieldErrorCode> {
  code: C;
  params: FieldErrorParams[C];
  detail: string;
}
const FIELD_ERROR_PARAM_NAMES: { readonly [C in FieldErrorCode]: readonly (keyof FieldErrorParams[C] & string)[] };
const FIELD_ERROR_CODES: readonly FieldErrorCode[];
function isFieldErrorCode(code: string): code is FieldErrorCode;

const ERROR_NAMESPACE: 'fastapi-viewsets';
const ERROR_NAMESPACE_PYDANTIC: 'pydantic';
const ERROR_NAMESPACE_DJANGO: 'django';

/** Assignable to vue-forms' `ErrorDescription`. */
interface ErrorDescription {
  readonly code: string;
  readonly params: Readonly<Record<string, unknown>>;
  readonly detail: string;
  readonly origin: 'server';
}

function isApiErrorBody(data: unknown): data is ApiErrorBody;
/** `error.response.data` when it is an `ApiErrorBody`, else `fastapi-viewsets.no_response` / `unexpected_response`. */
function errorBodyOf(error: unknown): ApiErrorBody;
function toErrorDescription(body: ApiErrorBody): ErrorDescription;
function toFieldErrors(body: ApiErrorBody): Record<string, ErrorDescription[]>;

The result of each conversion is described in Error codes → Frontend. The codes and their params are listed in Field error codes.

Individual operation mixins ​

CreateMixin <T, PK extends keyof T> ​

ts
create(data: Omit<T, PK>): ViewSetActionCall<T>;

BulkOnlyCreateMixin <T, PK extends keyof T> ​

ts
bulkCreate(data: Omit<T, PK>[]): ViewSetActionCall<T[]>;

BulkCreateMixin <T, PK extends keyof T> ​

Interface extends CreateMixin<T, PK> and BulkOnlyCreateMixin<T, PK>; actions spreads both.

ListMixin <T> ​

ts
list(params?: ListParams): ViewSetActionCall<T[]>;

PaginatedListMixin <T> ​

ts
listPage(params?: PageParams): ViewSetActionCall<PaginatedList<T>>;

CursorListMixin <T> ​

ts
listCursor(params?: CursorParams): ViewSetActionCall<CursorPage<T>>;

The three methods read the same GET {basePath}. Each sends X-List-Shape with its own shape - plain, paginated, cursor - and throws ListShapeMismatchError when the reply is in another one. A BE viewset that declares one shape does not read the header and answers in that shape, so a ViewSet declares the mixins of the shapes the BE viewset offers through list_shape and list_shapes. A shape the BE viewset's list_shapes leave out is a 422 fastapi-viewsets.unsupported_list_shape.

ListDefaultSort ​

A ViewSet declaring any of the three list mixins has defaultSort() as well. It is not an action and is not in ActionName:

ts
interface ListDefaultSort {
  defaultSort(): Promise<SortState>;
}
type ListAction = 'list' | 'listPage' | 'listCursor';
type DefaultSortOf<A> = [Extract<A, ListAction>] extends [never] ? unknown : ListDefaultSort;

defaultSort() resolves to the BE viewset's default_sort, [] when it declares none. It reads the sort parameter's default of GET {base} in the viewset's /schema, fetched over the ViewSet's transport once per instance and shared with the schema check. When the shared request fails, defaultSort() issues one of its own, repeated as any other call is; when that fails too, it rejects, and the next call fetches again. ViewSetProxyBase implements it, so a hand-written proxy has it too; RestProxy<M> and MuxwsProxy<M> carry it when M has list, listPage or listCursor (DefaultSortOf<keyof M>).

parseSort(sort: string | null | undefined): SortState reads a sort value as the BE does: a missing direction is asc, and an empty entry or one with any other direction is skipped. formatSort(state: readonly SortStateColumn[]): string writes one, '' for an empty state.

RetrieveMixin <K extends KeyType, T> ​

ts
retrieve(pk: K): ViewSetActionCall<T>;

UpdateMixin <K extends KeyType, T> ​

ts
update(pk: K, data: T): ViewSetActionCall<T>;
partialUpdate(pk: K, data: Partial<T>): ViewSetActionCall<T>;

BulkOnlyUpdateMixin <K extends KeyType, T> ​

ts
bulkUpdate(records: Record<K, T>): ViewSetActionCall<T[]>;
bulkPartialUpdate(records: Record<K, Partial<T>>): ViewSetActionCall<T[]>;

BulkUpdateMixin <K extends KeyType, T> ​

Interface extends UpdateMixin<K, T> and BulkOnlyUpdateMixin<K, T>; actions spreads both.

DestroyMixin <K extends KeyType> ​

ts
destroy(pk: K): ViewSetActionCall<DestroyReturnData<K>>;

BulkOnlyDestroyMixin <K extends KeyType> ​

ts
bulkDestroy(pks: K[]): ViewSetActionCall<BulkDestroyReturnData<K>>;

Keyed by pk: null for a deleted record, the failure's ApiErrorBody otherwise.

BulkDestroyMixin <K extends KeyType> ​

Interface extends DestroyMixin<K> and BulkOnlyDestroyMixin<K>; actions spreads both.

LookupMixin <L = LookupItem> ​

ts
lookup(params?: LookupParams): ViewSetActionCall<L[]>;

An array in params goes out as a repeated key (ids=1&ids=2) on both transports. On ViewSetProxyBase the method is lookup<I = LookupItem>(params?: LookupParams): ViewSetActionCall<I[]>.

lookupChoices ​

ts
interface LookupChoice {
  id: any;
  text: any;
  icon?: string;
}
type FetchLookupChoices = (queryValue?: string, idValue?: KeyType | KeyType[] | null) => Promise<LookupChoice[]>;
type LookupChoicesParams = Pick<LookupParams, 'q' | 'ids'>;
interface LookupChoicesSource<L> {
  lookup(params: LookupChoicesParams): PromiseLike<L[]>;
}

function lookupChoices(viewset: LookupChoicesSource<LookupItem>): FetchLookupChoices;
function lookupChoices<L>(viewset: LookupChoicesSource<L>, toChoice: (item: L) => LookupChoice): FetchLookupChoices;
function lookupChoices<L>(
  lookup: (params: LookupChoicesParams) => PromiseLike<L[]>,
  toChoice: (item: L) => LookupChoice,
): FetchLookupChoices;

Returns a fetchChoices for a @dynamicforms/vuetify-inputs df-select. LookupChoice has the shape of its SelectChoice, and FetchLookupChoices is assignable to its SelectFetchChoices; the package does not import @dynamicforms/vuetify-inputs.

The returned function:

  • with idValue neither null nor undefined: sends { ids }, idValue as an array; an empty array resolves to [] without a request;
  • otherwise: sends { q: queryValue }, or {} when queryValue is undefined or '';
  • converts each item with toChoice.
FormLookup callConversion
lookupChoices(viewset)viewset.lookup(params)pk → id, title → text, icon → icon, left out when null
lookupChoices(viewset, toChoice)viewset.lookup(params)toChoice(item)
lookupChoices(lookup, toChoice)lookup(params)toChoice(item)

lookup is called as a method of viewset. The first form is a compile error for a viewset whose lookup item type is not a LookupItem.

Combined viewset mixins ​

A composite restates no signature: its interface extends the leaves its actions names, so each action is written in exactly one place.

ReadOnlyViewSetMixin <K extends KeyType, T> ​

Interface extends ListMixin<T> and RetrieveMixin<K, T>; actions spreads both.

ViewSetMixin <K extends KeyType, T, PK extends keyof T> ​

Interface extends ReadOnlyViewSetMixin<K, T>, CreateMixin<T, PK>, UpdateMixin<K, T> and DestroyMixin<K>; actions spreads all four.

BulkViewSetMixin <K extends KeyType, T, PK extends keyof T> ​

Interface extends ViewSetMixin<K, T, PK>, BulkOnlyCreateMixin<T, PK>, BulkOnlyUpdateMixin<K, T> and BulkOnlyDestroyMixin<K>; actions spreads all four.

Released under the MIT License.