@motifx-community/ui 0.1.0-beta.14 → 0.1.0-beta.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +113 -0
- package/README.md +2 -2
- package/dist/components/diagram/Diagram.d.ts +607 -0
- package/dist/components/diagram/DiagramAutoPan.d.ts +17 -0
- package/dist/components/diagram/DiagramBends.d.ts +70 -0
- package/dist/components/diagram/DiagramDragging.d.ts +66 -0
- package/dist/components/diagram/DiagramEdgeView.d.ts +78 -0
- package/dist/components/diagram/DiagramGrid.d.ts +13 -0
- package/dist/components/diagram/DiagramHistory.d.ts +16 -0
- package/dist/components/diagram/DiagramLinks.d.ts +177 -0
- package/dist/components/diagram/DiagramMap.d.ts +62 -0
- package/dist/components/diagram/DiagramNodeView.d.ts +143 -0
- package/dist/components/diagram/DiagramOverview.d.ts +20 -0
- package/dist/components/diagram/DiagramPanning.d.ts +34 -0
- package/dist/components/diagram/diagram-alignment.d.ts +2 -0
- package/dist/components/diagram/diagram-auto-pan-host.d.ts +8 -0
- package/dist/components/diagram/diagram-background.d.ts +2 -0
- package/dist/components/diagram/diagram-bends-host.d.ts +17 -0
- package/dist/components/diagram/diagram-card-kind.d.ts +42 -0
- package/dist/components/diagram/diagram-card-node.d.ts +11 -0
- package/dist/components/diagram/diagram-center-options.d.ts +6 -0
- package/dist/components/diagram/diagram-change.d.ts +11 -0
- package/dist/components/diagram/diagram-class-member.d.ts +13 -0
- package/dist/components/diagram/diagram-class-node.d.ts +12 -0
- package/dist/components/diagram/diagram-column-checked-event-args.d.ts +9 -0
- package/dist/components/diagram/diagram-connected-event-args.d.ts +6 -0
- package/dist/components/diagram/diagram-connecting-event-args.d.ts +9 -0
- package/dist/components/diagram/diagram-connection.d.ts +7 -0
- package/dist/components/diagram/diagram-data.d.ts +12 -0
- package/dist/components/diagram/diagram-deleted-event-args.d.ts +8 -0
- package/dist/components/diagram/diagram-deleting-event-args.d.ts +9 -0
- package/dist/components/diagram/diagram-dragging-host.d.ts +47 -0
- package/dist/components/diagram/diagram-drawn-node.d.ts +10 -0
- package/dist/components/diagram/diagram-edge-end.d.ts +2 -0
- package/dist/components/diagram/diagram-edge-path.d.ts +5 -0
- package/dist/components/diagram/diagram-edge-reshaped-event-args.d.ts +8 -0
- package/dist/components/diagram/diagram-edge-reshaping-event-args.d.ts +6 -0
- package/dist/components/diagram/diagram-edge.d.ts +49 -0
- package/dist/components/diagram/diagram-edit.d.ts +10 -0
- package/dist/components/diagram/diagram-export-options.d.ts +14 -0
- package/dist/components/diagram/diagram-export.d.ts +28 -0
- package/dist/components/diagram/diagram-fit-options.d.ts +12 -0
- package/dist/components/diagram/diagram-history-changed-event-args.d.ts +14 -0
- package/dist/components/diagram/diagram-history-step.d.ts +9 -0
- package/dist/components/diagram/diagram-kinds.d.ts +9 -0
- package/dist/components/diagram/diagram-layered.d.ts +39 -0
- package/dist/components/diagram/diagram-layout-direction.d.ts +2 -0
- package/dist/components/diagram/diagram-layout-options.d.ts +24 -0
- package/dist/components/diagram/diagram-layout-type.d.ts +5 -0
- package/dist/components/diagram/diagram-layout.d.ts +33 -0
- package/dist/components/diagram/diagram-line-look.d.ts +6 -0
- package/dist/components/diagram/diagram-line.d.ts +11 -0
- package/dist/components/diagram/diagram-links-host.d.ts +45 -0
- package/dist/components/diagram/diagram-links-options.d.ts +7 -0
- package/dist/components/diagram/diagram-map-props.d.ts +10 -0
- package/dist/components/diagram/diagram-map-target.d.ts +27 -0
- package/dist/components/diagram/diagram-marker.d.ts +6 -0
- package/dist/components/diagram/diagram-mini-map-options.d.ts +13 -0
- package/dist/components/diagram/diagram-mini-map-position.d.ts +2 -0
- package/dist/components/diagram/diagram-node-context.d.ts +26 -0
- package/dist/components/diagram/diagram-node-host.d.ts +23 -0
- package/dist/components/diagram/diagram-node-kind.d.ts +43 -0
- package/dist/components/diagram/diagram-node-move.d.ts +11 -0
- package/dist/components/diagram/diagram-node-resized-event-args.d.ts +8 -0
- package/dist/components/diagram/diagram-node-resizing-event-args.d.ts +6 -0
- package/dist/components/diagram/diagram-node-size.d.ts +8 -0
- package/dist/components/diagram/diagram-node-status.d.ts +2 -0
- package/dist/components/diagram/diagram-node-toggled-event-args.d.ts +7 -0
- package/dist/components/diagram/diagram-node.d.ts +56 -0
- package/dist/components/diagram/diagram-nodes-moved-event-args.d.ts +6 -0
- package/dist/components/diagram/diagram-nodes-moving-event-args.d.ts +6 -0
- package/dist/components/diagram/diagram-panning-host.d.ts +19 -0
- package/dist/components/diagram/diagram-pasted-event-args.d.ts +7 -0
- package/dist/components/diagram/diagram-pasting-event-args.d.ts +11 -0
- package/dist/components/diagram/diagram-path-ends.d.ts +11 -0
- package/dist/components/diagram/diagram-path-result.d.ts +6 -0
- package/dist/components/diagram/diagram-paths.d.ts +35 -0
- package/dist/components/diagram/diagram-point.d.ts +5 -0
- package/dist/components/diagram/diagram-port-place.d.ts +9 -0
- package/dist/components/diagram/diagram-port.d.ts +27 -0
- package/dist/components/diagram/diagram-props.d.ts +159 -0
- package/dist/components/diagram/diagram-reconnected-event-args.d.ts +10 -0
- package/dist/components/diagram/diagram-reconnecting-event-args.d.ts +11 -0
- package/dist/components/diagram/diagram-rect.d.ts +7 -0
- package/dist/components/diagram/diagram-resize-side.d.ts +2 -0
- package/dist/components/diagram/diagram-route.d.ts +10 -0
- package/dist/components/diagram/diagram-selection-changed-event-args.d.ts +9 -0
- package/dist/components/diagram/diagram-selection.d.ts +5 -0
- package/dist/components/diagram/diagram-side.d.ts +2 -0
- package/dist/components/diagram/diagram-table-column.d.ts +13 -0
- package/dist/components/diagram/diagram-table-node.d.ts +12 -0
- package/dist/components/diagram/diagram-tree.d.ts +14 -0
- package/dist/components/diagram/diagram-viewport-changed-event-args.d.ts +8 -0
- package/dist/components/diagram/diagram-viewport-options.d.ts +5 -0
- package/dist/components/diagram/diagram-viewport.d.ts +6 -0
- package/dist/components/diagram/index.d.ts +65 -0
- package/dist/components/diagram/swallow-next-click.d.ts +5 -0
- package/dist/components/expressioneditor/ExpressionEditor.d.ts +111 -0
- package/dist/components/expressioneditor/expression-editor-props.d.ts +24 -0
- package/dist/components/expressioneditor/index.d.ts +2 -0
- package/dist/components/formlayout/FormLayout.d.ts +10 -3
- package/dist/components/formlayout/form-editor-type.d.ts +1 -1
- package/dist/components/formlayout/form-item.d.ts +4 -1
- package/dist/components/formlayout/form-layout-props.d.ts +1 -1
- package/dist/components/formlayout/index.d.ts +1 -0
- package/dist/components/formlayout/schema-items.d.ts +26 -0
- package/dist/components/pivotgrid/model/PivotAxisWindow.d.ts +53 -1
- package/dist/components/pivotgrid/model/PivotCellWindow.d.ts +2 -0
- package/dist/components/pivotgrid/model/PivotWindows.d.ts +3 -6
- package/dist/components/toolbar/Toolbar.d.ts +5 -3
- package/dist/core/control.d.ts +2 -0
- package/dist/core/keyboard.d.ts +5 -0
- package/dist/core/measure/index.d.ts +2 -0
- package/dist/core/measure/picture.d.ts +27 -0
- package/dist/core/shortcut-options.d.ts +5 -2
- package/dist/core/ui-strings.d.ts +191 -0
- package/dist/generated/tokens.d.ts +1615 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +11501 -705
- package/dist/index.js.map +1 -1
- package/dist/locales/en.json +180 -1
- package/dist/locales/tr.json +180 -1
- package/dist/styles.css +2262 -3
- package/dist/tokens/index.d.ts +1615 -0
- package/dist/tokens/index.js +1615 -0
- package/dist/tokens/index.js.map +1 -1
- package/dist/{tr-BGbF9uCs.js → tr-4GNbFdQh.js} +361 -3
- package/dist/{tr-BGbF9uCs.js.map → tr-4GNbFdQh.js.map} +1 -1
- package/docs/accordion.md +1 -1
- package/docs/actionsheet.md +1 -1
- package/docs/appbar.md +1 -1
- package/docs/appmenu-api.md +1 -1
- package/docs/appmenu-programmatic.md +1 -1
- package/docs/appmenu-search.md +1 -1
- package/docs/appmenu.md +1 -1
- package/docs/avatar.md +1 -1
- package/docs/badge.md +1 -1
- package/docs/bar-gauge-angles.md +1 -1
- package/docs/bar-gauge-data.md +1 -1
- package/docs/bar-gauge-labels.md +1 -1
- package/docs/bar-gauge.md +1 -1
- package/docs/barcode.md +1 -1
- package/docs/bottomnavigation.md +1 -1
- package/docs/bottomsheet.md +1 -1
- package/docs/breadcrumb.md +1 -1
- package/docs/button.md +1 -1
- package/docs/buttongroup.md +1 -1
- package/docs/buttons.md +1 -1
- package/docs/calendar.md +1 -1
- package/docs/card.md +1 -1
- package/docs/chart-bars.md +1 -1
- package/docs/chart-candles.md +1 -1
- package/docs/chart-funnel.md +1 -1
- package/docs/chart-heatmap.md +1 -1
- package/docs/chart-lines.md +1 -1
- package/docs/chart-live.md +1 -1
- package/docs/chart-pie.md +1 -1
- package/docs/chart-radar.md +1 -1
- package/docs/chart-ranges.md +1 -1
- package/docs/chart-references.md +1 -1
- package/docs/chart-scatter.md +1 -1
- package/docs/chart-waterfall.md +1 -1
- package/docs/chart-zoom.md +1 -1
- package/docs/chart.md +1 -1
- package/docs/chat.md +1 -1
- package/docs/checkbox.md +1 -1
- package/docs/chip.md +1 -1
- package/docs/choice.md +1 -1
- package/docs/colorbox.md +1 -1
- package/docs/combobox.md +1 -1
- package/docs/commands.md +1 -1
- package/docs/control.md +1 -1
- package/docs/data.md +2 -2
- package/docs/datagrid-api.md +1 -1
- package/docs/datagrid-bands.md +1 -1
- package/docs/datagrid-drag-select.md +1 -1
- package/docs/datagrid-drag.md +1 -1
- package/docs/datagrid-editing.md +1 -1
- package/docs/datagrid-filtering.md +1 -1
- package/docs/datagrid-forms.md +1 -1
- package/docs/datagrid-grouping.md +1 -1
- package/docs/datagrid-layout.md +1 -1
- package/docs/datagrid-lookups.md +1 -1
- package/docs/datagrid-master-detail.md +1 -1
- package/docs/datagrid-scrolling.md +1 -1
- package/docs/datagrid-selection.md +1 -1
- package/docs/datagrid.md +1 -1
- package/docs/datalayer-api.md +491 -0
- package/docs/datalayer-changes.md +501 -0
- package/docs/datalayer-odata.md +998 -0
- package/docs/datalayer-pivot.md +850 -0
- package/docs/datalayer-queries.md +516 -0
- package/docs/datalayer-rest.md +529 -0
- package/docs/datalayer-soap.md +576 -0
- package/docs/datalayer-source.md +464 -0
- package/docs/datalayer.md +264 -0
- package/docs/datebox.md +1 -1
- package/docs/daterangebox.md +1 -1
- package/docs/diagram-api.md +200 -0
- package/docs/diagram-commands.md +79 -0
- package/docs/diagram-connections.md +157 -0
- package/docs/diagram-custom-nodes.md +325 -0
- package/docs/diagram-designer.md +816 -0
- package/docs/diagram-editing.md +62 -0
- package/docs/diagram-flow.md +157 -0
- package/docs/diagram-keyboard.md +58 -0
- package/docs/diagram-layout.md +354 -0
- package/docs/diagram-nodes.md +206 -0
- package/docs/diagram-tables.md +212 -0
- package/docs/diagram.md +217 -0
- package/docs/display.md +1 -1
- package/docs/draggable.md +1 -1
- package/docs/drawer.md +1 -1
- package/docs/dropdown.md +1 -1
- package/docs/editors.md +1 -1
- package/docs/expressioneditor.md +469 -0
- package/docs/expressions.md +431 -0
- package/docs/feedback.md +1 -1
- package/docs/fileuploader.md +1 -1
- package/docs/filterbuilder.md +1 -1
- package/docs/formlayout-schema.md +143 -0
- package/docs/formlayout.md +16 -4
- package/docs/foundations.md +1 -1
- package/docs/gallery.md +1 -1
- package/docs/gauge-base.md +1 -1
- package/docs/gauge-circular.md +1 -1
- package/docs/gauge-dashboards.md +1 -1
- package/docs/gauge-linear.md +1 -1
- package/docs/gauge-markers.md +1 -1
- package/docs/gauge-marks.md +1 -1
- package/docs/gauge-ranges.md +1 -1
- package/docs/gauge-scales.md +1 -1
- package/docs/gauge.md +1 -1
- package/docs/home.md +1 -1
- package/docs/keyboard.md +2 -2
- package/docs/language.md +1 -1
- package/docs/layout.md +1 -1
- package/docs/listbox.md +1 -1
- package/docs/loadpanel.md +1 -1
- package/docs/lookup.md +1 -1
- package/docs/markdown.md +1 -1
- package/docs/menus-api.md +1 -1
- package/docs/menus-context.md +1 -1
- package/docs/menus-customization.md +1 -1
- package/docs/menus-merging.md +1 -1
- package/docs/menus-programmatic.md +1 -1
- package/docs/menus.md +1 -1
- package/docs/multiview.md +1 -1
- package/docs/navigation.md +1 -1
- package/docs/numberbox.md +1 -1
- package/docs/otpinput.md +1 -1
- package/docs/pagination.md +1 -1
- package/docs/pivotgrid-api.md +1 -1
- package/docs/pivotgrid-chart.md +1 -1
- package/docs/pivotgrid-drilldown.md +1 -1
- package/docs/pivotgrid-export.md +1 -1
- package/docs/pivotgrid-fields.md +1 -1
- package/docs/pivotgrid-keyboard.md +1 -1
- package/docs/pivotgrid-layout.md +1 -1
- package/docs/pivotgrid-panel.md +1 -1
- package/docs/pivotgrid-remote.md +122 -44
- package/docs/pivotgrid-sorting.md +3 -3
- package/docs/pivotgrid-state.md +1 -1
- package/docs/pivotgrid-summaries.md +1 -1
- package/docs/pivotgrid.md +1 -1
- package/docs/popover.md +1 -1
- package/docs/progress.md +1 -1
- package/docs/qrcode.md +1 -1
- package/docs/radiogroup.md +1 -1
- package/docs/rating.md +1 -1
- package/docs/resizable.md +1 -1
- package/docs/ribbonmenu-api.md +1 -1
- package/docs/ribbonmenu-commands.md +1 -1
- package/docs/ribbonmenu-customization.md +1 -1
- package/docs/ribbonmenu-display.md +1 -1
- package/docs/ribbonmenu-layouts.md +1 -1
- package/docs/ribbonmenu-programmatic.md +1 -1
- package/docs/ribbonmenu.md +1 -1
- package/docs/scheduler-agenda.md +1 -1
- package/docs/scheduler-big-data.md +1 -1
- package/docs/scheduler-editing.md +1 -1
- package/docs/scheduler-form.md +1 -1
- package/docs/scheduler-icalendar.md +1 -1
- package/docs/scheduler-mobile.md +1 -1
- package/docs/scheduler-recurrence.md +1 -1
- package/docs/scheduler-resources.md +1 -1
- package/docs/scheduler-timeline.md +1 -1
- package/docs/scheduler.md +1 -1
- package/docs/scrollview.md +1 -1
- package/docs/shortcuteditor.md +1 -1
- package/docs/showcase-flowstudio.md +61 -0
- package/docs/showcase-home.md +1 -1
- package/docs/showcase-mail.md +1 -1
- package/docs/showcase.md +1 -1
- package/docs/signature.md +1 -1
- package/docs/skeleton.md +1 -1
- package/docs/slider.md +1 -1
- package/docs/sortable.md +1 -1
- package/docs/sparkline.md +1 -1
- package/docs/speeddial.md +1 -1
- package/docs/splitter.md +1 -1
- package/docs/stepper.md +1 -1
- package/docs/switch.md +1 -1
- package/docs/tabdocs-dock.md +1 -1
- package/docs/tabdocs-drag.md +1 -1
- package/docs/tabdocs-menus.md +1 -1
- package/docs/tabdocs-mobile.md +1 -1
- package/docs/tabdocs-tabs.md +1 -1
- package/docs/tabdocs-windows.md +1 -1
- package/docs/tabdocs-workspace.md +1 -1
- package/docs/tabdocs.md +1 -1
- package/docs/tabs.md +1 -1
- package/docs/tagbox.md +1 -1
- package/docs/textarea.md +1 -1
- package/docs/textbox.md +1 -1
- package/docs/tileview.md +1 -1
- package/docs/timeline.md +1 -1
- package/docs/toast.md +1 -1
- package/docs/tokens.md +324 -1
- package/docs/toolbar-api.md +1 -1
- package/docs/toolbar-customization.md +1 -1
- package/docs/toolbar.md +1 -1
- package/docs/tooltip.md +1 -1
- package/docs/treeview.md +1 -1
- package/docs/validationsummary.md +1 -1
- package/docs/window.md +1 -1
- package/docs/wizard.md +1 -1
- package/llms-full.txt +10142 -462
- package/llms.txt +32 -1
- package/package.json +2 -2
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
# Data layer: REST
|
|
2
|
+
|
|
3
|
+
> Data layer · @motifx-community/data 0.1.0-beta.3
|
|
4
|
+
|
|
5
|
+
`RestAdapter` connects a data source to a REST endpoint: one URL loads, finds, inserts, updates and removes rows over HTTP and JSON. The protocol has a plain default, and every part of it can be replaced to match an existing service.
|
|
6
|
+
|
|
7
|
+
## Creating a REST adapter
|
|
8
|
+
|
|
9
|
+
`url` names the collection and `key` the key field; several field names make a composite key (the key is then an object of those fields), and a function reads the key from a row. The adapter also takes the options every adapter shares (`fields`, `locale`, `capabilities`, `sortValue`, `filterValue`, `compare`), described in the [API reference](datalayer-api.md), and the HTTP options of [Requests](#requests).
|
|
10
|
+
|
|
11
|
+
```tsx
|
|
12
|
+
import { data } from '@motifx-community/data';
|
|
13
|
+
|
|
14
|
+
const orders = new data.RestAdapter<Order, number>({
|
|
15
|
+
url: '/api/orders',
|
|
16
|
+
key: 'id',
|
|
17
|
+
timeoutMs: 15_000,
|
|
18
|
+
retry: { retries: 2 },
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const source = new data.DataSource<Order, number>({ adapter: orders, pageSize: 20 });
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## The default protocol
|
|
25
|
+
|
|
26
|
+
Five requests cover the whole adapter. Bodies are sent as JSON with `Content-Type: application/json`, and every request asks for JSON with `Accept: application/json`.
|
|
27
|
+
|
|
28
|
+
| Request | Operation | Answer |
|
|
29
|
+
| --- | --- | --- |
|
|
30
|
+
| `GET url` | Loads rows. The query carries the paging, the sorting and the filter (below). | The rows: an array, or an object such as `{ "rows": [...], "total": 123 }`. |
|
|
31
|
+
| `GET url/key` | Finds one row (`byKey`). `select` and `expand` go as comma-joined query parameters. | The row as JSON. A `404` resolves to `undefined`. |
|
|
32
|
+
| `POST url` | Inserts a row. The body is the new row as JSON. | The saved row, or only the fields the server adds (the new key); an empty answer keeps the sent values. |
|
|
33
|
+
| `PATCH url/key` | Updates a row. The body holds only the changed fields. `updateMethod` picks another method. | Read in the same way as the answer to an insert. |
|
|
34
|
+
| `DELETE url/key` | Removes a row. | Any success status; the body is ignored. |
|
|
35
|
+
|
|
36
|
+
A load writes its query with these parameters; the query string encodes spaces as `%20` and leaves `$`, `,`, `/`, `:` and `@` readable.
|
|
37
|
+
|
|
38
|
+
| Parameter | Description |
|
|
39
|
+
| --- | --- |
|
|
40
|
+
| `skip` | Rows to skip, a plain number; sent only when a page is asked for. |
|
|
41
|
+
| `take` | Rows to take, a plain number; sent only when a page is asked for. |
|
|
42
|
+
| `count=true` | Sent when the caller asks for the number of matching rows. The answer must then carry the total. |
|
|
43
|
+
| `sort=name,-date` | The sort fields, comma-joined, `-` before a descending one; sent only when there is a sort. |
|
|
44
|
+
| `filter` | The [filter expression](datalayer-queries.md) as JSON: `{"field":"city","op":"=","value":"İzmir"}`. |
|
|
45
|
+
| `select` | The fields to return, comma-joined. |
|
|
46
|
+
| `expand` | Related data to include, comma-joined; meant for backends that take it. |
|
|
47
|
+
| `…params` | Every entry of the operation's `params` option is appended as it is, and overrides a parameter of the same name. |
|
|
48
|
+
|
|
49
|
+
```tsx
|
|
50
|
+
GET /api/orders?skip=5&take=5&count=true&sort=-amount&filter={"field":"city","op":"=","value":"İzmir"}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
A load's answer is read by `defaultReadRows`. An array is taken as the rows themselves; when a count was asked for and no page was, its length serves as the total. Any other answer is read as an object: the rows are its first array among `rows`, `items`, `data` and `value`, the total its first number among `total`, `totalCount`, `count` and `@odata.count`. When `count=true` was sent, the answer must carry the total; a load without one fails with `MJD104`. A total that stands in a header instead is read with `readRows` ([below](#custom)).
|
|
54
|
+
|
|
55
|
+
An insert or update may answer with the whole saved row, with only the fields the server adds or changes, or with nothing. An answer that holds every sent field replaces them, a smaller one is merged over the sent values, and an empty one keeps them; `insert` resolves to the saved row either way, so a key the server assigns reaches the caller.
|
|
56
|
+
|
|
57
|
+
```tsx
|
|
58
|
+
/** An order, as the service in the page stores it. */
|
|
59
|
+
export interface Order {
|
|
60
|
+
id: number;
|
|
61
|
+
customer: string;
|
|
62
|
+
city: string;
|
|
63
|
+
amount: number;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const CUSTOMERS = ['Aylin Demir', 'Jonas Weber', 'Mia Novak', 'Elif Aksoy', 'Leo Fischer', 'Sara Lund'];
|
|
67
|
+
const CITIES = ['Ankara', 'İzmir', 'Vienna', 'Ljubljana', 'Oslo'];
|
|
68
|
+
|
|
69
|
+
/** `n` invented orders, the same ones every time. */
|
|
70
|
+
export function makeOrders(n: number): Order[] {
|
|
71
|
+
return Array.from({ length: n }, (_, i) => ({
|
|
72
|
+
id: i + 1,
|
|
73
|
+
customer: CUSTOMERS[(i * 5) % CUSTOMERS.length],
|
|
74
|
+
city: CITIES[(i * 3) % CITIES.length],
|
|
75
|
+
amount: (((i + 7) * 7919) % 48_000) / 100,
|
|
76
|
+
}));
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
The service above runs in the page: the adapter's `fetch` option answers the default protocol from orders in memory, computing each load with `queryArray`, the data layer's memory engine. The log lists every request as it was sent, the URL decoded. Adding, changing or deleting a row sends one request and no reload: the data source applies the saved change to the rows it holds, as [DataSource](datalayer-source.md#keys) describes.
|
|
81
|
+
|
|
82
|
+
## Writing the server
|
|
83
|
+
|
|
84
|
+
A backend that answers the default protocol needs no adapter options at all. What it must do:
|
|
85
|
+
|
|
86
|
+
- Answer JSON with a JSON `Content-Type`. A body of another type is kept as text, and a load then finds no rows.
|
|
87
|
+
|
|
88
|
+
- Apply the query in order: `filter`, then `sort`, then `skip` and `take`. With `count=true`, return the number of rows the filter leaves, not the length of the page.
|
|
89
|
+
|
|
90
|
+
- Answer an insert with the saved row, or at least with the fields the server assigned, the new key first of all. An update may answer the row or nothing; a remove's answer is ignored. A `204` and an empty body are both read as no body.
|
|
91
|
+
|
|
92
|
+
- Answer `404` for a key that does not exist: `byKey` then resolves to `undefined`, and an update or remove fails as `MJD204`.
|
|
93
|
+
|
|
94
|
+
- Reject invalid values with `400` or `422` and say why: a message in `message`, `error`, `error.message` or `title`, and messages by field in `errors`, an object whose keys are field names, as an HTTP problem-details answer writes them. They surface as the `fields` of a `DataError` with code `MJD202`.
|
|
95
|
+
|
|
96
|
+
- Use `409` for a key that exists, `412` for a row changed since it was read, and `428` for a save that needs the row as it was read; [Requests](#requests) maps every status to its error code.
|
|
97
|
+
|
|
98
|
+
## Changing the protocol
|
|
99
|
+
|
|
100
|
+
`itemUrl` names the address of one row where it is not `url/key`. `updateMethod` picks the method of an update, `'PUT'` for a service that replaces rows. `loadQuery` writes a load's query as an object of parameters; entries that are `null` or `undefined` are left out. `readRows` reads a load's answer into `{ rows, total }` and also gets the response, so a total that stands in a header is read too. `readSaved` reads what an insert or update answers.
|
|
101
|
+
|
|
102
|
+
```tsx
|
|
103
|
+
const orders = new data.RestAdapter<Order, number>({
|
|
104
|
+
url: '/api/orders',
|
|
105
|
+
key: 'id',
|
|
106
|
+
itemUrl: (key) => `/api/orders(${key})`,
|
|
107
|
+
updateMethod: 'PUT',
|
|
108
|
+
loadQuery: (o) => ({ ...data.defaultLoadQuery(o), take: undefined, limit: o.take }),
|
|
109
|
+
readRows: (body, options, response) => ({
|
|
110
|
+
rows: body as Order[],
|
|
111
|
+
total: Number(response.headers.get('X-Total-Count')),
|
|
112
|
+
}),
|
|
113
|
+
});
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
The defaults are exported as `defaultLoadQuery`, `defaultReadRows` and `defaultReadSaved`, so a replacement can build on them instead of starting over, as `loadQuery` does above.
|
|
117
|
+
|
|
118
|
+
## Batches
|
|
119
|
+
|
|
120
|
+
A save that carries several changes sends them one by one, unless `batch` names an endpoint that takes them in one request. The changes go to `batch.url` (`POST` by default) with the body `batch.write(changes)` writes; each change is `{ type: 'insert', data }`, `{ type: 'update', key, data, original? }` or `{ type: 'remove', key, original? }`. `batch.read(body, changes)` reads the answer into one result per change, in order: `{ ok: true, row? }`, the row read as a single save's answer is, or `{ ok: false, error }`. A change the answer misses fails with `MJD104`; a failed change does not stop the others, and `save` resolves with one outcome per change. When several changes travel together is decided by the caller: [Tracking and saving changes](datalayer-changes.md) explains the save modes.
|
|
121
|
+
|
|
122
|
+
```tsx
|
|
123
|
+
batch: {
|
|
124
|
+
url: '/api/orders/batch',
|
|
125
|
+
write: (changes) => changes,
|
|
126
|
+
read: (body, changes) =>
|
|
127
|
+
(body as { ok: boolean; row?: Order; message?: string }[]).map((r) =>
|
|
128
|
+
r.ok ? { ok: true, row: r.row } : { ok: false, error: new Error(r.message) },
|
|
129
|
+
),
|
|
130
|
+
},
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## What the endpoint cannot do
|
|
134
|
+
|
|
135
|
+
A REST endpoint is taken to filter, sort, page, count and select, and to insert, update and remove; grouping and summaries always run in memory over the rows it answers, and pivots need `pivot`. When a service does less, `capabilities` turns features off, `capabilities: { filter: false }` for example: the adapter stops sending that part of a query, loads the rows without it and runs the rest in memory, moving paging and counting there too where filtering or sorting in memory needs every matching row first. The [overview](datalayer.md#capabilities) explains what runs where.
|
|
136
|
+
|
|
137
|
+
## Requests
|
|
138
|
+
|
|
139
|
+
`RestAdapter` extends `HttpAdapter`, as `ODataAdapter` and `SoapAdapter` do; the options and events of this section are shared by all three. Every request starts as an `HttpRequest`: the operation, the method, the URL without its query, the query as `URLSearchParams`, the headers, the body and the caller's signal. `Accept: application/json` is set first, then the `headers` option writes over it: fixed headers, or a function called for every request, asynchronous if need be. `onRequesting` fires next and `beforeSend` runs after it; both may change any part of the request or set `cancel`, which fails the operation with `MJD106` before anything is sent.
|
|
140
|
+
|
|
141
|
+
The request is sent with the `fetch` option, the global `fetch` by default. `timeoutMs` fails a try that has no answer in time (`MJD102`). `retry` retries with the core's `RetryOptions`, and only transient failures by default: no answer, a timeout, or status 408, 429 or 5xx; each try gets the whole `timeoutMs` again. `resilience` replaces `retry` with a whole core policy, a circuit breaker, a bulkhead or a rate limiter among them; a request such a policy holds back fails as `MJD107`, `MJD108` or `MJD109`.
|
|
142
|
+
|
|
143
|
+
`afterReceive` sees every answer, error statuses too, before the adapter reads it, and may change `status` or `body`, or throw; `onResponded` fires after it, with `durationMs`. Both run per try, so a retried request reports each answer. A status outside 200–299 then becomes a `DataError`: `readError` reads the backend's own error format first (return nothing to fall back), the body is read for a message (`message`, `error`, `error.message` or `title`) and for messages by field (`errors` as an object, or `error.details` as `[{ target, message }]`), and the status picks the code. The [API reference](datalayer-api.md#errors) describes every code.
|
|
144
|
+
|
|
145
|
+
| Code | Kind | When |
|
|
146
|
+
| --- | --- | --- |
|
|
147
|
+
| `MJD101` | `network` | No answer: the request itself failed. |
|
|
148
|
+
| `MJD102` | `timeout` | No answer within `timeoutMs`. |
|
|
149
|
+
| `MJD103` | `http` | An error status no other code claims; `status` holds it, and the message is read from the body. |
|
|
150
|
+
| `MJD104` | `parse` | The answer could not be read: a body that is not valid JSON, or rows or a total missing where they are required. |
|
|
151
|
+
| `MJD105` | `abort` | The caller's `signal` cancelled the request. |
|
|
152
|
+
| `MJD106` | `abort` | An `onRequesting` listener or `beforeSend` set `cancel`. |
|
|
153
|
+
| `MJD107 MJD108 MJD109` | `held` | A `resilience` policy held the request back: the circuit is open, too many requests are waiting, or the rate limit is reached. |
|
|
154
|
+
| `MJD202` | `validation` | A `400` or `422` with a message or messages by field; `fields` holds them. Without either text the status falls to `MJD103`. |
|
|
155
|
+
| `MJD203` | `conflict` | A `409`: a row with this key exists. |
|
|
156
|
+
| `MJD204` | `not-found` | A `404` on `byKey` (which resolves to `undefined` instead of failing), update or remove. |
|
|
157
|
+
| `MJD205` | `conflict` | A `412`: the row was changed elsewhere since it was read. |
|
|
158
|
+
| `MJD305` | `invalid` | A `428`: the backend needs the row as it was read (`original`) to save this change. |
|
|
159
|
+
|
|
160
|
+
```tsx
|
|
161
|
+
/** An order, as the service in the page stores it. */
|
|
162
|
+
export interface Order {
|
|
163
|
+
id: number;
|
|
164
|
+
customer: string;
|
|
165
|
+
city: string;
|
|
166
|
+
amount: number;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const CUSTOMERS = ['Aylin Demir', 'Jonas Weber', 'Mia Novak', 'Elif Aksoy', 'Leo Fischer', 'Sara Lund'];
|
|
170
|
+
const CITIES = ['Ankara', 'İzmir', 'Vienna', 'Ljubljana', 'Oslo'];
|
|
171
|
+
|
|
172
|
+
/** `n` invented orders, the same ones every time. */
|
|
173
|
+
export function makeOrders(n: number): Order[] {
|
|
174
|
+
return Array.from({ length: n }, (_, i) => ({
|
|
175
|
+
id: i + 1,
|
|
176
|
+
customer: CUSTOMERS[(i * 5) % CUSTOMERS.length],
|
|
177
|
+
city: CITIES[(i * 3) % CITIES.length],
|
|
178
|
+
amount: (((i + 7) * 7919) % 48_000) / 100,
|
|
179
|
+
}));
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Above, a `headers` function stamps a fresh token on every request, `readRows` unwraps an envelope of the service's own, and a rejected save surfaces as a `DataError` with code `MJD202` and its messages by field. The common envelopes, `rows`, `items`, `data` or `value` with their totals, need no `readRows`: the default reads them.
|
|
184
|
+
|
|
185
|
+
## Pivots
|
|
186
|
+
|
|
187
|
+
`pivot: { url }` names an endpoint that computes pivots: a pivot's options go to it as a JSON body (`POST` by default), and the same endpoint answers the parts a view loads as it scrolls, each body marked with `kind`. Without `pivot`, the matching rows are loaded and the pivot is grouped in memory. The bodies, the answers and the options (`method`, `write`, `read`, `window`, `blocks`) are described in [Pivots and loading in parts](datalayer-pivot.md#rest).
|
|
188
|
+
|
|
189
|
+
## API reference
|
|
190
|
+
|
|
191
|
+
`RestAdapterOptions` extends `HttpAdapterOptions` below and the shared `DataAdapterOptions` (`key`, `fields`, `locale`, `capabilities`, `sortValue`, `filterValue`, `compare`), described in the [API reference](datalayer-api.md).
|
|
192
|
+
|
|
193
|
+
| Option | Default | Description |
|
|
194
|
+
| --- | --- | --- |
|
|
195
|
+
| `url` | — | The address of the collection: loads and inserts go to it, and `url/key` names one row. |
|
|
196
|
+
| `itemUrl` | `url/key` | The address of one row, `(key) => string`. The default appends the key to `url`; a composite key writes one segment per key field, each URI-encoded. |
|
|
197
|
+
| `updateMethod` | `'PATCH'` | The HTTP method of an update. |
|
|
198
|
+
| `loadQuery` | `defaultLoadQuery` | Writes the query parameters of a load from the [load options](datalayer-api.md); entries that are `null` or `undefined` are left out. |
|
|
199
|
+
| `readRows` | `defaultReadRows` | Reads a load's answer into `{ rows, total }`. It also gets the `HttpResponse`, for a total that stands in a header. |
|
|
200
|
+
| `readSaved` | `defaultReadSaved` | Reads what an insert or update answers: the body when it is an object, else nothing. |
|
|
201
|
+
| `batch` | — | An endpoint that takes many changes in one request ([Batches](#batch)). |
|
|
202
|
+
| `pivot` | — | An endpoint that computes pivots ([Pivots](datalayer-pivot.md#rest)); without it a pivot is grouped in memory. |
|
|
203
|
+
|
|
204
|
+
### HttpAdapterOptions
|
|
205
|
+
|
|
206
|
+
| Option | Default | Description |
|
|
207
|
+
| --- | --- | --- |
|
|
208
|
+
| `fetch` | the global `fetch` | Sends the requests: give a wrapped `fetch`, or a function that answers in the page, as the examples here do. |
|
|
209
|
+
| `headers` | — | Fixed headers, or a function called for every request (the current token, for example); it may answer asynchronously. |
|
|
210
|
+
| `credentials` | — | The `credentials` of every request (`'include'` sends cookies to another origin). |
|
|
211
|
+
| `beforeSend` | — | Runs before a request is sent and may change any part of it or set `cancel`; it may be async. |
|
|
212
|
+
| `afterReceive` | — | Sees every answer (error statuses too) before the adapter reads it; it may change `status` or `body`, or throw. |
|
|
213
|
+
| `timeoutMs` | — | Fails a try that has no answer in this many milliseconds (`MJD102`); without it, a request waits as long as the browser does. |
|
|
214
|
+
| `retry` | — | The core's `RetryOptions` (`retries`, `delay`, `backoff`, `jitter`, `onRetry`); only transient failures are retried by default. |
|
|
215
|
+
| `resilience` | — | A whole core resilience policy, used instead of `retry`. |
|
|
216
|
+
| `readError` | — | Reads an error answer in the backend's own format into a `DataError`; return nothing for the built-in reader. |
|
|
217
|
+
| `errorTextLength` | `300` | An error answer that is plain text becomes the message up to this many characters. |
|
|
218
|
+
|
|
219
|
+
Every HTTP adapter also has two events:
|
|
220
|
+
|
|
221
|
+
| Event | Description |
|
|
222
|
+
| --- | --- |
|
|
223
|
+
| `onRequesting` | Occurs for every request before it is sent, with the `HttpRequest`; listeners may change it or set `cancel`. |
|
|
224
|
+
| `onResponded` | Occurs for every answer, with the `HttpResponse`; a retried request reports each try. |
|
|
225
|
+
|
|
226
|
+
### HttpRequest
|
|
227
|
+
|
|
228
|
+
| Member | Description |
|
|
229
|
+
| --- | --- |
|
|
230
|
+
| `operation` | What the request does: `'load'`, `'count'`, `'byKey'`, `'insert'`, `'update'`, `'remove'` or `'save'`. Read-only. |
|
|
231
|
+
| `method` | The HTTP method. |
|
|
232
|
+
| `url` | The address without its query parameters; those stand in `query`. |
|
|
233
|
+
| `query` | The query parameters, a `URLSearchParams`. |
|
|
234
|
+
| `headers` | The headers, a `Headers`; `Accept: application/json` is already set. |
|
|
235
|
+
| `data` | The body as a value, sent as JSON with `Content-Type: application/json` unless `body` is set. |
|
|
236
|
+
| `body` | The raw body (`BodyInit`); set, it is sent as it is and `data` is left alone. |
|
|
237
|
+
| `credentials` | The request's `credentials`. |
|
|
238
|
+
| `signal` | The caller's `AbortSignal`, when one was given. Read-only. |
|
|
239
|
+
| `cancel` | Set it `true` to cancel: nothing is sent and the operation fails with `MJD106`. |
|
|
240
|
+
|
|
241
|
+
### HttpResponse
|
|
242
|
+
|
|
243
|
+
| Member | Description |
|
|
244
|
+
| --- | --- |
|
|
245
|
+
| `request` | The request this is the answer to. |
|
|
246
|
+
| `status` | The HTTP status; `afterReceive` may change it. |
|
|
247
|
+
| `statusText` | The status text. |
|
|
248
|
+
| `headers` | The answer's headers. |
|
|
249
|
+
| `body` | The parsed JSON, the text when the answer is not JSON, or `null` when it is empty; `afterReceive` may change it. |
|
|
250
|
+
| `durationMs` | How long the try took, in milliseconds. |
|
|
251
|
+
|
|
252
|
+
### RestBatch
|
|
253
|
+
|
|
254
|
+
| Member | Default | Description |
|
|
255
|
+
| --- | --- | --- |
|
|
256
|
+
| `url` | — | The address the changes are sent to. |
|
|
257
|
+
| `method` | `'POST'` | The HTTP method. |
|
|
258
|
+
| `write` | — | Writes the body from the changes; it is sent as JSON. |
|
|
259
|
+
| `read` | — | Reads the answer into one result per change, in order: `{ ok: true, row? }` or `{ ok: false, error }`. |
|
|
260
|
+
|
|
261
|
+
## Feedback
|
|
262
|
+
|
|
263
|
+
Loading issues…
|
|
264
|
+
|
|
265
|
+
## Example files
|
|
266
|
+
|
|
267
|
+
`Protocol.tsx`
|
|
268
|
+
|
|
269
|
+
```tsx
|
|
270
|
+
import { reactive } from '@motifx/core';
|
|
271
|
+
import { data } from '@motifx-community/data';
|
|
272
|
+
import { Button, DataGrid, Stack, type GridColumn } from '@motifx-community/ui';
|
|
273
|
+
import { makeOrders, type Order } from './orders';
|
|
274
|
+
import { ordersService, type ServiceCall } from './orders-service';
|
|
275
|
+
|
|
276
|
+
const columns: GridColumn<Order>[] = [
|
|
277
|
+
{ field: 'id', title: 'No', type: 'number', width: 70 },
|
|
278
|
+
{ field: 'customer', title: 'Customer', flex: 1 },
|
|
279
|
+
{ field: 'city', title: 'City', width: 110 },
|
|
280
|
+
{ field: 'amount', title: 'Amount', type: 'number', width: 110 },
|
|
281
|
+
];
|
|
282
|
+
|
|
283
|
+
/** Every request of the default protocol, answered by the service in the page and listed as it is sent. */
|
|
284
|
+
export default function Protocol() {
|
|
285
|
+
const s = reactive({ log: [] as ServiceCall[], filtered: false, sorted: false, note: '' });
|
|
286
|
+
const adapter = new data.RestAdapter<Order, number>({
|
|
287
|
+
url: '/api/orders',
|
|
288
|
+
key: 'id',
|
|
289
|
+
fetch: ordersService(makeOrders(23), (call) => {
|
|
290
|
+
s.log.unshift(call);
|
|
291
|
+
if (s.log.length > 12) s.log.pop();
|
|
292
|
+
}),
|
|
293
|
+
});
|
|
294
|
+
const orders = new data.DataSource<Order, number>({ adapter, loadMode: 'page', pageSize: 5 });
|
|
295
|
+
const first = () => orders.rows[0];
|
|
296
|
+
|
|
297
|
+
return (
|
|
298
|
+
<>
|
|
299
|
+
<Stack orientation="horizontal" wrap align="center">
|
|
300
|
+
<Button
|
|
301
|
+
text="Filter: İzmir"
|
|
302
|
+
variant={() => (s.filtered ? 'solid' : 'outline')}
|
|
303
|
+
onclick={() => {
|
|
304
|
+
s.filtered = !s.filtered;
|
|
305
|
+
void orders.setFilter(s.filtered ? data.where('city', '=', 'İzmir') : null);
|
|
306
|
+
}}
|
|
307
|
+
/>
|
|
308
|
+
<Button
|
|
309
|
+
text="Sort by amount"
|
|
310
|
+
variant={() => (s.sorted ? 'solid' : 'outline')}
|
|
311
|
+
onclick={() => {
|
|
312
|
+
s.sorted = !s.sorted;
|
|
313
|
+
void orders.setSort(s.sorted ? [{ field: 'amount', dir: 'desc' }] : []);
|
|
314
|
+
}}
|
|
315
|
+
/>
|
|
316
|
+
<Button text="Next page" variant="outline" onclick={() => void orders.setPage((orders.pageIndex + 1) % (orders.pageCount || 1))} />
|
|
317
|
+
<Button text="Find order 7" variant="outline" onclick={() => void adapter.byKey(7).then((row) => (s.note = row ? `Order 7: ${row.customer}, ${row.amount}` : 'No order 7.'))} />
|
|
318
|
+
<Button text="Add" variant="outline" onclick={() => void adapter.insert({ customer: 'Mia Novak', city: 'Vienna', amount: 180 })} />
|
|
319
|
+
<Button
|
|
320
|
+
text="Change the first row"
|
|
321
|
+
variant="outline"
|
|
322
|
+
onclick={() => {
|
|
323
|
+
const row = first();
|
|
324
|
+
if (row) void adapter.update(row.id, { amount: Math.round(row.amount) + 5 });
|
|
325
|
+
}}
|
|
326
|
+
/>
|
|
327
|
+
<Button
|
|
328
|
+
text="Delete the first row"
|
|
329
|
+
variant="outline"
|
|
330
|
+
onclick={() => {
|
|
331
|
+
const row = first();
|
|
332
|
+
if (row) void adapter.remove(row.id);
|
|
333
|
+
}}
|
|
334
|
+
/>
|
|
335
|
+
</Stack>
|
|
336
|
+
<Stack>
|
|
337
|
+
<DataGrid
|
|
338
|
+
class="rest-protocol-grid"
|
|
339
|
+
style="block-size: 17rem"
|
|
340
|
+
dataSource={orders}
|
|
341
|
+
columns={columns}
|
|
342
|
+
label="Orders from the service in the page"
|
|
343
|
+
locale="en"
|
|
344
|
+
/>
|
|
345
|
+
<div role="log" aria-label="Requests" tabindex="0" style="max-block-size: 12rem; overflow: auto; font-size: 0.85em">
|
|
346
|
+
{s.log.map((c) => (
|
|
347
|
+
<div key={c.id} style="margin-block-end: 0.4rem">
|
|
348
|
+
<div>
|
|
349
|
+
<code>{`${c.method} ${c.url}`}</code> <span>{`→ ${c.status}`}</span>
|
|
350
|
+
</div>
|
|
351
|
+
{c.body ? (
|
|
352
|
+
<div>
|
|
353
|
+
<code>{c.body}</code>
|
|
354
|
+
</div>
|
|
355
|
+
) : null}
|
|
356
|
+
</div>
|
|
357
|
+
))}
|
|
358
|
+
</div>
|
|
359
|
+
</Stack>
|
|
360
|
+
<output>{() => s.note}</output>
|
|
361
|
+
</>
|
|
362
|
+
);
|
|
363
|
+
}
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
`orders-service.ts`
|
|
367
|
+
|
|
368
|
+
```tsx
|
|
369
|
+
import { data } from '@motifx-community/data';
|
|
370
|
+
import type { Order } from './orders';
|
|
371
|
+
|
|
372
|
+
/** One request as the service saw it: the method, the URL decoded, the body, and the status it answered. */
|
|
373
|
+
export interface ServiceCall {
|
|
374
|
+
id: number;
|
|
375
|
+
method: string;
|
|
376
|
+
url: string;
|
|
377
|
+
body?: string;
|
|
378
|
+
status: number;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
let callId = 0;
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* A REST service in the page at `/api/orders`: it answers the default protocol from orders in memory,
|
|
385
|
+
* computing each load with the data layer's memory engine, and reports every call. Nothing leaves the page.
|
|
386
|
+
*/
|
|
387
|
+
export function ordersService(rows: Order[], report: (call: ServiceCall) => void) {
|
|
388
|
+
let nextId = rows.length + 1;
|
|
389
|
+
const json = (body: unknown, status = 200) =>
|
|
390
|
+
new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
|
|
391
|
+
|
|
392
|
+
return async (input: string, init: RequestInit): Promise<Response> => {
|
|
393
|
+
const url = new URL(input, location.origin);
|
|
394
|
+
const answer = (response: Response) => {
|
|
395
|
+
report({ id: ++callId, method: init.method ?? 'GET', url: decodeURIComponent(input), body: init.body ? String(init.body) : undefined, status: response.status });
|
|
396
|
+
return response;
|
|
397
|
+
};
|
|
398
|
+
|
|
399
|
+
if (url.pathname === '/api/orders' && init.method === 'GET') {
|
|
400
|
+
const q = url.searchParams;
|
|
401
|
+
const sort = q
|
|
402
|
+
.get('sort')
|
|
403
|
+
?.split(',')
|
|
404
|
+
.map((s): data.SortItem => (s.startsWith('-') ? { field: s.slice(1), dir: 'desc' } : { field: s, dir: 'asc' }));
|
|
405
|
+
const result = data.queryArray(rows, {
|
|
406
|
+
filter: q.has('filter') ? JSON.parse(q.get('filter')!) : undefined,
|
|
407
|
+
sort,
|
|
408
|
+
skip: q.has('skip') ? Number(q.get('skip')) : undefined,
|
|
409
|
+
take: q.has('take') ? Number(q.get('take')) : undefined,
|
|
410
|
+
count: q.get('count') === 'true',
|
|
411
|
+
});
|
|
412
|
+
return answer(json({ rows: result.rows, total: result.total }));
|
|
413
|
+
}
|
|
414
|
+
if (url.pathname === '/api/orders' && init.method === 'POST') {
|
|
415
|
+
const row = { ...(JSON.parse(String(init.body)) as Order), id: nextId++ };
|
|
416
|
+
rows.push(row);
|
|
417
|
+
return answer(json(row, 201));
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const id = Number(url.pathname.slice('/api/orders/'.length));
|
|
421
|
+
const row = rows.find((r) => r.id === id);
|
|
422
|
+
if (!row) return answer(json({ message: `No order ${id}.` }, 404));
|
|
423
|
+
if (init.method === 'GET') return answer(json(row));
|
|
424
|
+
if (init.method === 'PATCH') return answer(json(Object.assign(row, JSON.parse(String(init.body)))));
|
|
425
|
+
rows.splice(rows.indexOf(row), 1);
|
|
426
|
+
return answer(new Response(null, { status: 204 }));
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
`orders.ts`
|
|
432
|
+
|
|
433
|
+
```tsx
|
|
434
|
+
/** An order, as the service in the page stores it. */
|
|
435
|
+
export interface Order {
|
|
436
|
+
id: number;
|
|
437
|
+
customer: string;
|
|
438
|
+
city: string;
|
|
439
|
+
amount: number;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const CUSTOMERS = ['Aylin Demir', 'Jonas Weber', 'Mia Novak', 'Elif Aksoy', 'Leo Fischer', 'Sara Lund'];
|
|
443
|
+
const CITIES = ['Ankara', 'İzmir', 'Vienna', 'Ljubljana', 'Oslo'];
|
|
444
|
+
|
|
445
|
+
/** `n` invented orders, the same ones every time. */
|
|
446
|
+
export function makeOrders(n: number): Order[] {
|
|
447
|
+
return Array.from({ length: n }, (_, i) => ({
|
|
448
|
+
id: i + 1,
|
|
449
|
+
customer: CUSTOMERS[(i * 5) % CUSTOMERS.length],
|
|
450
|
+
city: CITIES[(i * 3) % CITIES.length],
|
|
451
|
+
amount: (((i + 7) * 7919) % 48_000) / 100,
|
|
452
|
+
}));
|
|
453
|
+
}
|
|
454
|
+
```
|
|
455
|
+
|
|
456
|
+
`Requests.tsx`
|
|
457
|
+
|
|
458
|
+
```tsx
|
|
459
|
+
import { reactive } from '@motifx/core';
|
|
460
|
+
import { data } from '@motifx-community/data';
|
|
461
|
+
import { Button, Stack } from '@motifx-community/ui';
|
|
462
|
+
import type { Order } from './orders';
|
|
463
|
+
|
|
464
|
+
const ROWS: Order[] = [
|
|
465
|
+
{ id: 1, customer: 'Aylin Demir', city: 'İzmir', amount: 420 },
|
|
466
|
+
{ id: 2, customer: 'Jonas Weber', city: 'Vienna', amount: 310 },
|
|
467
|
+
{ id: 3, customer: 'Mia Novak', city: 'Ljubljana', amount: 150 },
|
|
468
|
+
];
|
|
469
|
+
|
|
470
|
+
/** A service in the page that wraps loads in an envelope of its own and rejects every save with field messages. */
|
|
471
|
+
function envelopeService(report: (line: string) => void) {
|
|
472
|
+
const json = (body: unknown, status = 200) =>
|
|
473
|
+
new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
|
|
474
|
+
return async (input: string, init: RequestInit): Promise<Response> => {
|
|
475
|
+
report(`${init.method} ${decodeURIComponent(input)} · authorization: ${new Headers(init.headers).get('authorization') ?? ''}`);
|
|
476
|
+
if (init.method === 'GET') return json({ result: { items: ROWS }, meta: { matches: ROWS.length } });
|
|
477
|
+
return json({ title: 'The order is not valid.', errors: { amount: ['Must be more than zero.'] } }, 422);
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** A token header on every request, an envelope read with `readRows`, and an error answer become a `DataError`. */
|
|
482
|
+
export default function Requests() {
|
|
483
|
+
const s = reactive({ lines: [] as { id: number; text: string }[] });
|
|
484
|
+
let lineId = 0;
|
|
485
|
+
let tokenNo = 0;
|
|
486
|
+
const say = (text: string) => s.lines.unshift({ id: ++lineId, text });
|
|
487
|
+
|
|
488
|
+
const adapter = new data.RestAdapter<Order, number>({
|
|
489
|
+
url: '/api/orders',
|
|
490
|
+
key: 'id',
|
|
491
|
+
fetch: envelopeService(say),
|
|
492
|
+
headers: () => ({ Authorization: `Bearer token-${++tokenNo}` }),
|
|
493
|
+
readRows: (body) => {
|
|
494
|
+
const b = body as { result: { items: Order[] }; meta: { matches: number } };
|
|
495
|
+
return { rows: b.result.items, total: b.meta.matches };
|
|
496
|
+
},
|
|
497
|
+
});
|
|
498
|
+
adapter.onResponded((r) => say(`→ ${r.status} ${r.statusText} in ${r.durationMs} ms`));
|
|
499
|
+
|
|
500
|
+
const load = async () => {
|
|
501
|
+
const result = await adapter.load({ count: true });
|
|
502
|
+
say(`→ ${result.rows.length} rows, total ${result.total}`);
|
|
503
|
+
};
|
|
504
|
+
const save = async () => {
|
|
505
|
+
try {
|
|
506
|
+
await adapter.insert({ customer: 'New customer', amount: 0 });
|
|
507
|
+
} catch (error) {
|
|
508
|
+
const e = error as data.DataError;
|
|
509
|
+
say(`→ ${e.code} (${e.kind}): ${e.plainMessage} · fields: ${JSON.stringify(e.fields)}`);
|
|
510
|
+
}
|
|
511
|
+
};
|
|
512
|
+
|
|
513
|
+
return (
|
|
514
|
+
<>
|
|
515
|
+
<Stack orientation="horizontal" wrap align="center">
|
|
516
|
+
<Button text="Load" variant="outline" onclick={() => void load()} />
|
|
517
|
+
<Button text="Save an invalid order" variant="outline" onclick={() => void save()} />
|
|
518
|
+
</Stack>
|
|
519
|
+
<div role="log" aria-label="Requests" style="font-size: 0.85em">
|
|
520
|
+
{s.lines.map((l) => (
|
|
521
|
+
<div key={l.id}>
|
|
522
|
+
<code>{l.text}</code>
|
|
523
|
+
</div>
|
|
524
|
+
))}
|
|
525
|
+
</div>
|
|
526
|
+
</>
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
```
|