@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,998 @@
|
|
|
1
|
+
# Data layer: OData
|
|
2
|
+
|
|
3
|
+
> Data layer · @motifx-community/data 0.1.0-beta.3
|
|
4
|
+
|
|
5
|
+
`ODataAdapter` reads and writes an OData v4 entity set. Filtering, sorting, paging, counting, `$select` and `$expand` run on the service, summaries and pivots too where it supports `$apply`, and writes carry the row's `@odata.etag`, so a change made elsewhere is detected rather than overwritten.
|
|
6
|
+
|
|
7
|
+
## Creating an OData adapter
|
|
8
|
+
|
|
9
|
+
```tsx
|
|
10
|
+
import { data } from '@motifx-community/data';
|
|
11
|
+
|
|
12
|
+
const orders = new data.ODataAdapter<Order, number>({
|
|
13
|
+
url: 'https://host/odata/Orders',
|
|
14
|
+
key: 'OrderId',
|
|
15
|
+
fields: { OrderedOn: 'datetime', ShippedOn: 'date', RowGuid: 'guid' },
|
|
16
|
+
collections: ['Tags'],
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const page = await orders.load({
|
|
20
|
+
filter: data.where('ShipCity', 'contains', 'ber'),
|
|
21
|
+
sort: [{ field: 'OrderedOn', dir: 'desc' }],
|
|
22
|
+
take: 50,
|
|
23
|
+
count: true,
|
|
24
|
+
expand: ['Customer', 'Lines.Product'],
|
|
25
|
+
});
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
`url` names the entity set: loads read it with `GET`, inserts post to it, and the address up to the set's name is the service root, used for `$batch` and relative next links. `key` names the key field or fields; `byKey`, `update` and `remove` address one row as `url(5)`, `url('4-B')` or `url(OrderId=7,Line=2)`, the literals written by the key fields' types. A key the default cannot write, or a `key` given as a function, takes `itemUrl`, a function from the key to the row's address.
|
|
29
|
+
|
|
30
|
+
`fields` declares the field types, which decide how values are written in `$filter` and in key addresses:
|
|
31
|
+
|
|
32
|
+
| Type | Literal | Notes |
|
|
33
|
+
| --- | --- | --- |
|
|
34
|
+
| `string` | `'O''Brien'` | Text in single quotes; a quote in the value is doubled. |
|
|
35
|
+
| `number` | `12.5` | `Infinity` is written as `INF`, `-Infinity` as `-INF`. |
|
|
36
|
+
| `boolean` | `true` | Written as `true` or `false`. |
|
|
37
|
+
| `date` | `2024-03-05` | A calendar day: a `Date` value is written as its local day, the way `date` fields compare in memory. |
|
|
38
|
+
| `datetime` | `2024-03-05T10:00:00.000Z` | A moment, in ISO form. |
|
|
39
|
+
| `guid` | `0f8fad5b-d9cb-469f-a165-70867728950e` | Without quotes; a value that is not a GUID is refused. |
|
|
40
|
+
|
|
41
|
+
A value a declared type cannot hold, such as text in a `number` field or a malformed GUID, rejects the operation with `MJD302` before any request is sent. `collections` names the fields that hold a list of values; [conditions on them](#filters) are written with `any()`. `readRow` changes each row read from the service, such as date strings into `Date` values.
|
|
42
|
+
|
|
43
|
+
The adapter extends the HTTP options every HTTP adapter shares, `fetch`, `headers`, `beforeSend`, `timeoutMs`, `retry` and the rest: see [Requests](datalayer-rest.md#requests). The shared adapter contract, its options and its events are on [Custom adapters and API](datalayer-api.md).
|
|
44
|
+
|
|
45
|
+
## Queries on the service
|
|
46
|
+
|
|
47
|
+
`load` turns its [load options](datalayer-queries.md) into OData system query options and reads the rows from the `value` array of the answer, with `@odata.count` as `total` when it asked for one:
|
|
48
|
+
|
|
49
|
+
| Load option | Query option | What is sent |
|
|
50
|
+
| --- | --- | --- |
|
|
51
|
+
| `filter` | `$filter` | The text of [How filters are written](#filters). A filter that keeps every row sends no `$filter` at all; one that keeps none is sent as `$filter=false`. |
|
|
52
|
+
| `sort` | `$orderby` | The fields joined with commas, `desc` after a descending one: `Freight desc,Customer/Name`. A dotted path is written with slashes. |
|
|
53
|
+
| `skip` | `$skip` | Left off at 0. |
|
|
54
|
+
| `take` | `$top` | `take: 0` together with `count` asks for the total alone, which is how `count()` counts. |
|
|
55
|
+
| `count` | `$count=true` | The service answers the number of matching rows in `@odata.count`, returned as `total`. |
|
|
56
|
+
| `select` | `$select` | The field paths, joined with commas, dots written as slashes. |
|
|
57
|
+
| `expand` | `$expand` | Related data. A nested path becomes a nested expand: `Lines.Product` is sent as `Lines($expand=Product)`. A path that already holds `(` is used as written. |
|
|
58
|
+
| `params` | — | Sent as they are: query parameters of the service's own, such as `$search`. |
|
|
59
|
+
|
|
60
|
+
`byKey` sends `$select` and `$expand` the same way, to the row's address. A load with `group` is not translated: OData has no grouped row answer, so the rows the filter leaves are loaded whole and grouped, sorted, paged and counted in memory ([Filtering, sorting and grouping](datalayer-queries.md)).
|
|
61
|
+
|
|
62
|
+
The example builds a query from its controls and sends it through the adapter. The service runs in the page, over twelve invented orders, and reads nothing but the URL it is asked, so the rows can never contradict the request; the URL is shown decoded. An emptied city box drops its condition from the `$filter`, and with every filter control cleared no `$filter` is sent at all.
|
|
63
|
+
|
|
64
|
+
```tsx
|
|
65
|
+
// Invented rows behind the in-page OData service: orders with a customer, lines with a product, and tags.
|
|
66
|
+
export interface Customer {
|
|
67
|
+
id: number;
|
|
68
|
+
name: string;
|
|
69
|
+
city: string;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface Product {
|
|
73
|
+
id: number;
|
|
74
|
+
name: string;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface OrderLine {
|
|
78
|
+
id: number;
|
|
79
|
+
order: number;
|
|
80
|
+
product: number;
|
|
81
|
+
units: number;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface Order {
|
|
85
|
+
id: number;
|
|
86
|
+
customerId: number;
|
|
87
|
+
city: string;
|
|
88
|
+
/** A calendar day, as an OData date property answers. */
|
|
89
|
+
orderedOn: string;
|
|
90
|
+
freight: number;
|
|
91
|
+
tags: string[];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export const customers: Customer[] = [
|
|
95
|
+
{ id: 1, name: 'Elif Demir', city: 'Oslo' },
|
|
96
|
+
{ id: 2, name: 'Can Yılmaz', city: 'Berlin' },
|
|
97
|
+
{ id: 3, name: 'Zeynep Kaya', city: 'İzmir' },
|
|
98
|
+
{ id: 4, name: 'Mert Şahin', city: 'Lisbon' },
|
|
99
|
+
];
|
|
100
|
+
|
|
101
|
+
export const products: Product[] = [
|
|
102
|
+
{ id: 1, name: 'Walnut desk' },
|
|
103
|
+
{ id: 2, name: 'Brass lamp' },
|
|
104
|
+
{ id: 3, name: 'Wool rug' },
|
|
105
|
+
{ id: 4, name: 'Oak shelf' },
|
|
106
|
+
{ id: 5, name: 'Glass vase' },
|
|
107
|
+
];
|
|
108
|
+
|
|
109
|
+
export const orders: Order[] = [
|
|
110
|
+
{ id: 1, customerId: 1, city: 'Oslo', orderedOn: '2026-01-12', freight: 42.5, tags: ['express'] },
|
|
111
|
+
{ id: 2, customerId: 2, city: 'Berlin', orderedOn: '2026-02-03', freight: 18, tags: ['gift'] },
|
|
112
|
+
{ id: 3, customerId: 3, city: 'İzmir', orderedOn: '2026-02-21', freight: 96.2, tags: ['fragile', 'express'] },
|
|
113
|
+
{ id: 4, customerId: 1, city: 'Bergen', orderedOn: '2026-03-15', freight: 7.75, tags: [] },
|
|
114
|
+
{ id: 5, customerId: 4, city: 'Lisbon', orderedOn: '2026-04-02', freight: 130, tags: ['fragile'] },
|
|
115
|
+
{ id: 6, customerId: 2, city: 'Hamburg', orderedOn: '2026-05-19', freight: 55.4, tags: ['express', 'gift'] },
|
|
116
|
+
{ id: 7, customerId: 3, city: 'Ankara', orderedOn: '2026-06-08', freight: 23.9, tags: [] },
|
|
117
|
+
{ id: 8, customerId: 1, city: 'Oslo', orderedOn: '2026-07-27', freight: 61, tags: ['gift'] },
|
|
118
|
+
{ id: 9, customerId: 4, city: 'Porto', orderedOn: '2026-08-14', freight: 12.3, tags: ['express'] },
|
|
119
|
+
{ id: 10, customerId: 2, city: 'Berlin', orderedOn: '2026-09-05', freight: 88.8, tags: ['fragile'] },
|
|
120
|
+
{ id: 11, customerId: 3, city: 'İzmir', orderedOn: '2026-10-22', freight: 34, tags: ['gift', 'express'] },
|
|
121
|
+
{ id: 12, customerId: 1, city: 'Bodø', orderedOn: '2026-11-10', freight: 150.25, tags: [] },
|
|
122
|
+
];
|
|
123
|
+
|
|
124
|
+
export const orderLines: OrderLine[] = [
|
|
125
|
+
{ id: 1, order: 1, product: 1, units: 2 },
|
|
126
|
+
{ id: 2, order: 1, product: 3, units: 1 },
|
|
127
|
+
{ id: 3, order: 2, product: 2, units: 4 },
|
|
128
|
+
{ id: 4, order: 3, product: 5, units: 6 },
|
|
129
|
+
{ id: 5, order: 4, product: 4, units: 1 },
|
|
130
|
+
{ id: 6, order: 5, product: 5, units: 12 },
|
|
131
|
+
{ id: 7, order: 6, product: 2, units: 2 },
|
|
132
|
+
{ id: 8, order: 6, product: 1, units: 1 },
|
|
133
|
+
{ id: 9, order: 7, product: 3, units: 3 },
|
|
134
|
+
{ id: 10, order: 8, product: 4, units: 5 },
|
|
135
|
+
{ id: 11, order: 9, product: 2, units: 1 },
|
|
136
|
+
{ id: 12, order: 10, product: 5, units: 8 },
|
|
137
|
+
{ id: 13, order: 11, product: 1, units: 1 },
|
|
138
|
+
{ id: 14, order: 12, product: 3, units: 2 },
|
|
139
|
+
];
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## How filters are written
|
|
143
|
+
|
|
144
|
+
The `$filter` keeps exactly the rows the same [filter](datalayer-queries.md) keeps in memory. Text compares without case through `tolower()`, the value lowered in the adapter's `locale`; `ignoreCase: false`, or `caseSensitive` on one condition, compares as written. Blank means `null`, and for a declared `string` field also empty or only spaces.
|
|
145
|
+
|
|
146
|
+
| Operator | What is written | Empty values |
|
|
147
|
+
| --- | --- | --- |
|
|
148
|
+
| `=` | `tolower(City) eq 'oslo'` | An empty value becomes the blank test of `isblank`. |
|
|
149
|
+
| `<>` | `tolower(City) ne 'oslo'` | Rows without a value are kept; an empty value becomes the test of `isnotblank`. |
|
|
150
|
+
| `< <= > >=` | `Freight gt 5` | An empty value keeps no rows. |
|
|
151
|
+
| `between` | `(Freight ge 10 and Freight le 20)` | A `null` end is left off; with both ends open, the rows with a value are kept. |
|
|
152
|
+
| `in` | `(Freight eq 1 or Freight eq 2)` | An empty value in the list compares with `null`; an empty list keeps no rows. |
|
|
153
|
+
| `notin` | `(tolower(City) ne 'oslo' and City ne null)` | Rows without a value are kept; an empty list keeps every row. |
|
|
154
|
+
| `contains startswith endswith` | `contains(tolower(City),'os')` | An empty text value filters nothing out, like an empty filter box. |
|
|
155
|
+
| `notcontains` | `(City eq null or not contains(tolower(City),'os'))` | Rows without a value are kept; an empty text value filters nothing out. |
|
|
156
|
+
| `isblank` | `(City eq null or trim(City) eq '')` | For a field not declared `string`, only `City eq null`. |
|
|
157
|
+
| `isnotblank` | `(City ne null and trim(City) ne '')` | For a field not declared `string`, only `City ne null`. |
|
|
158
|
+
|
|
159
|
+
A condition that keeps every row drops out of an `and`, and one that keeps no rows decides it; in an `or` the roles turn around. A filter reduced to keeping every row sends no `$filter`; one reduced to keeping none is sent as `$filter=false`.
|
|
160
|
+
|
|
161
|
+
A condition on a field named in `collections` holds when one of the row's values passes it: `where('Tags', '=', 'gift')` is written as `Tags/any(x: tolower(x) eq 'gift')`. With `<>`, `notin` and `notcontains` it holds when none does, `not Tags/any(…)`, and a list is blank when none of its values is not blank, an empty list too: `isblank` becomes `not Tags/any(x: x ne null)`.
|
|
162
|
+
|
|
163
|
+
A condition with `interval` compares the field through OData's date functions: `year(OrderedOn) eq 2024`, months with `month()`, days of the month with `day()`, calendar days with `date()`, quarters as `(month(OrderedOn) add 2) div 3`, and a number interval as `floor(Freight div 100.0) mul 100`. No OData function reads the day of the week: `canFilter` returns `false` for such a filter, and a caller that can split its filter keeps that condition in memory and sends the rest, as the kit's pivot drill-down does. A `load` given a filter the service cannot write is refused with `MJD302`.
|
|
164
|
+
|
|
165
|
+
`toODataFilter` writes the same text for requests of your own, and `odataLiteral` writes one value:
|
|
166
|
+
|
|
167
|
+
```tsx
|
|
168
|
+
import { data } from '@motifx-community/data';
|
|
169
|
+
|
|
170
|
+
const text = data.toODataFilter(
|
|
171
|
+
data.and(data.where('City', 'contains', 'ber'), data.where('OrderedOn', '>=', new Date(2026, 0, 1)))!,
|
|
172
|
+
{ fields: { OrderedOn: 'date' }, locale: 'en-US' },
|
|
173
|
+
); // contains(tolower(City),'ber') and OrderedOn ge 2026-01-01
|
|
174
|
+
|
|
175
|
+
const name = data.odataLiteral("O'Brien", 'string'); // 'O''Brien'
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
## Paging by the service
|
|
179
|
+
|
|
180
|
+
A service may answer fewer rows than asked and point to the rest with `@odata.nextLink`. The adapter follows the link until the rows asked for are there, so one `load` resolves to the whole page it was asked, whatever the service's own page size; past `take` rows it stops following and cuts the extra rows of the last answer. A relative link is resolved against the service root. Answers to `$apply` reads are followed the same way, or the groups past the first answer would be missing. `followNextLink: false` keeps each first answer as it is.
|
|
181
|
+
|
|
182
|
+
## Aggregation
|
|
183
|
+
|
|
184
|
+
With `aggregation: true` the service computes summaries: a load with `summary` sends one `$apply` read beside the row read, and a load that asks only for summaries (`take: 0`, no `count`) sends the `$apply` read alone. The summary types map to the OData aggregation methods, `avg` to `average` and `countDistinct` to `countdistinct`. Without `aggregation`, the matching rows are loaded and summed in memory.
|
|
185
|
+
|
|
186
|
+
```tsx
|
|
187
|
+
GET https://host/odata/Orders?$apply=filter(Freight gt 5)/aggregate(Freight with sum as s0,$count as s1)
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Pivots are computed on the service the same way: one `$apply` per pair of depths of the axes, the rows filtered, grouped and aggregated in one expression, and the parts a view reads as it scrolls, the members of a level paged with `$orderby`, `$skip`, `$top` and `$count`. A service orders empty values its own way, so the empty member never reaches `$orderby`: it is read apart and placed here. [Pivots and loading in parts](datalayer-pivot.md#odata) describes the requests, the orders by a measure and what a server answers.
|
|
191
|
+
|
|
192
|
+
```tsx
|
|
193
|
+
GET https://host/odata/Orders?$apply=filter(Freight gt 5)/groupby((ShipCountry,ShipCity),aggregate($count as _n,Freight with sum as _m0))
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
The object form of `aggregation` says what the service does beyond `aggregate` and `groupby`. A pivot level with an interval needs `compute: true`, a service that computes values (`year()`, `month()`, `day()`, `date()`, `floor()`); without it such a pivot is grouped in memory, and one by the day of the week always is. `conditional: true` says the service takes `case` in `compute` (OData 4.01), which lets members ordered by a measure in a member of the other axis be counted and paged there. `pageSize` asks long ordered reads in pages of that many rows, and `batch: true` sends a pivot's reads in one `$batch` request. A `keep` of expanded members becomes a plain `filter(…)` with the same date functions and needs no `compute`.
|
|
197
|
+
|
|
198
|
+
## Writing
|
|
199
|
+
|
|
200
|
+
`insert` posts the values to the entity set, `update` sends `PATCH` to the row's address with the changed fields only (`updateMethod: 'PUT'` changes the method for a service that replaces the row), and `remove` sends `DELETE`. Values of `date` fields go as days, and `@odata.` annotations stay out of the body. [ChangeTracker](datalayer-changes.md) builds these calls from edits and passes `original` by itself.
|
|
201
|
+
|
|
202
|
+
`update` and `remove` send the `@odata.etag` of the row given as `original` as `If-Match`, so the service saves only over the version that was read. A row changed elsewhere answers 412, and the save rejects with `MJD205`; a service that needs the version and did not get one answers 428, which becomes `MJD305`. Writes ask for the saved row back with `Prefer: return=representation` and resolve to it, the service's computed fields and new `@odata.etag` included; an answer without a body still carries the new version in its `ETag` header. `returnSavedRow: false` turns the preference off.
|
|
203
|
+
|
|
204
|
+
With `batch: true`, `save` sends all changes as one `$batch` request, a `multipart/mixed` `POST` to the service root plus `$batch`. Every change is one part with its own method, address and headers, addressed in full, and `Prefer: odata.continue-on-error` asks the service to try them all, as `save` promises; the answers are matched to the changes by `Content-ID`, one outcome each. `batch: { allOrNothing: true }` puts the changes in one change set instead: the service saves all of them or none, no `Prefer` is sent, and a failed change set answers one error, which every change of the save gets.
|
|
205
|
+
|
|
206
|
+
```tsx
|
|
207
|
+
POST https://host/odata/$batch
|
|
208
|
+
OData-Version: 4.0
|
|
209
|
+
Content-Type: multipart/mixed; boundary=batch_1
|
|
210
|
+
Prefer: odata.continue-on-error
|
|
211
|
+
|
|
212
|
+
--batch_1
|
|
213
|
+
Content-Type: application/http
|
|
214
|
+
Content-ID: 1
|
|
215
|
+
|
|
216
|
+
PATCH https://host/odata/Orders(1) HTTP/1.1
|
|
217
|
+
Content-Type: application/json
|
|
218
|
+
If-Match: W/"3"
|
|
219
|
+
Prefer: return=representation
|
|
220
|
+
|
|
221
|
+
{"Freight":12}
|
|
222
|
+
--batch_1
|
|
223
|
+
Content-Type: application/http
|
|
224
|
+
Content-ID: 2
|
|
225
|
+
|
|
226
|
+
DELETE https://host/odata/Orders(2) HTTP/1.1
|
|
227
|
+
If-Match: W/"5"
|
|
228
|
+
|
|
229
|
+
--batch_1--
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
An error answer is read the OData way: `error.message` becomes the message and `error.details` the messages by field, so a validation answer rejects with `MJD202` and its `fields` filled. The [REST page](datalayer-rest.md#requests) lists how every status maps to an error code.
|
|
233
|
+
|
|
234
|
+
The service of the example runs in the page and holds two orders with their versions. Saving shows the `If-Match` header; after the row is changed elsewhere the same save answers 412 and rejects with `MJD205`, and reading the row again saves over the fresh version. Saving without `original` sends no `If-Match`, which this service answers with 428: `MJD305`. The batch button saves both freights in one `$batch`, whose exact body the request pane shows; with a stale version, `allOrNothing` fails both changes, and without it only the stale one.
|
|
235
|
+
|
|
236
|
+
```tsx
|
|
237
|
+
// An OData v4 service with two orders, running in the page: writes save only over the version named in
|
|
238
|
+
// If-Match, and a $batch body is read part by part, a change set as one unit.
|
|
239
|
+
|
|
240
|
+
interface Stored {
|
|
241
|
+
id: number;
|
|
242
|
+
customer: string;
|
|
243
|
+
freight: number;
|
|
244
|
+
version: number;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
interface Answer {
|
|
248
|
+
status: number;
|
|
249
|
+
statusText: string;
|
|
250
|
+
headers?: Record<string, string>;
|
|
251
|
+
body?: unknown;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
interface BatchPart {
|
|
255
|
+
contentId: string;
|
|
256
|
+
method: string;
|
|
257
|
+
url: string;
|
|
258
|
+
headers: Record<string, string>;
|
|
259
|
+
body?: string;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const fail = (status: number, statusText: string, message: string): Answer => ({ status, statusText, body: { error: { code: '', message } } });
|
|
263
|
+
const splitOnce = (text: string, mark: string): [string, string] => {
|
|
264
|
+
const at = text.indexOf(mark);
|
|
265
|
+
return at < 0 ? [text, ''] : [text.slice(0, at), text.slice(at + mark.length)];
|
|
266
|
+
};
|
|
267
|
+
const boundaryOf = (contentType: string) => /boundary="?([^";\s]+)"?/i.exec(contentType)?.[1] ?? '';
|
|
268
|
+
|
|
269
|
+
export class WriteService {
|
|
270
|
+
private readonly rows = new Map<number, Stored>([
|
|
271
|
+
[1, { id: 1, customer: 'Elif Demir', freight: 42.5, version: 1 }],
|
|
272
|
+
[2, { id: 2, customer: 'Can Yılmaz', freight: 18, version: 1 }],
|
|
273
|
+
]);
|
|
274
|
+
|
|
275
|
+
constructor(private readonly asked: (method: string, url: string, headers: Headers, body: string | undefined) => void) {}
|
|
276
|
+
|
|
277
|
+
/** Another session saves the row: its version moves on. */
|
|
278
|
+
changeElsewhere(id: number): void {
|
|
279
|
+
const row = this.rows.get(id)!;
|
|
280
|
+
row.freight = Math.round((row.freight + 2.5) * 100) / 100;
|
|
281
|
+
row.version++;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
row(id: number): Record<string, unknown> {
|
|
285
|
+
return this.entity(this.rows.get(id)!);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
readonly fetch = async (input: string, init: RequestInit): Promise<Response> => {
|
|
289
|
+
const headers = new Headers(init.headers);
|
|
290
|
+
const body = init.body === undefined || init.body === null ? undefined : String(init.body);
|
|
291
|
+
this.asked(init.method ?? 'GET', input, headers, body);
|
|
292
|
+
if (new URL(input).pathname.endsWith('/$batch')) return this.batch(body ?? '', headers.get('content-type') ?? '');
|
|
293
|
+
const record: Record<string, string> = {};
|
|
294
|
+
headers.forEach((value, name) => (record[name] = value));
|
|
295
|
+
const a = this.answer(init.method ?? 'GET', input, record, body);
|
|
296
|
+
const head = { ...(a.body === undefined ? {} : { 'content-type': 'application/json' }), ...a.headers };
|
|
297
|
+
return new Response(a.body === undefined ? null : JSON.stringify(a.body), { status: a.status, statusText: a.statusText, headers: head });
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
private entity(row: Stored): Record<string, unknown> {
|
|
301
|
+
return { '@odata.etag': `W/"${row.version}"`, id: row.id, customer: row.customer, freight: row.freight };
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// What would stop this request; null when it saves.
|
|
305
|
+
private trouble(method: string, row: Stored | undefined, headers: Record<string, string>): Answer | null {
|
|
306
|
+
if (!row) return fail(404, 'Not Found', 'No order with this key.');
|
|
307
|
+
if (method !== 'PATCH' && method !== 'GET') return fail(405, 'Method Not Allowed', `This service does not take ${method}.`);
|
|
308
|
+
if (method === 'GET') return null;
|
|
309
|
+
const ifMatch = headers['if-match'];
|
|
310
|
+
if (!ifMatch) return fail(428, 'Precondition Required', 'This service saves only over a version: send If-Match.');
|
|
311
|
+
if (ifMatch !== `W/"${row.version}"`) return fail(412, 'Precondition Failed', 'The order was changed by someone else.');
|
|
312
|
+
return null;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
private answer(method: string, url: string, headers: Record<string, string>, body: string | undefined): Answer {
|
|
316
|
+
const id = Number(/\((\d+)\)/.exec(new URL(url).pathname)?.[1]);
|
|
317
|
+
const row = this.rows.get(id);
|
|
318
|
+
const stopped = this.trouble(method, row, headers);
|
|
319
|
+
if (stopped || !row) return stopped ?? fail(404, 'Not Found', 'No order with this key.');
|
|
320
|
+
if (method === 'GET') return { status: 200, statusText: 'OK', body: this.entity(row) };
|
|
321
|
+
const changes = JSON.parse(body ?? '{}') as Partial<Stored>;
|
|
322
|
+
if (typeof changes.freight === 'number') row.freight = changes.freight;
|
|
323
|
+
if (typeof changes.customer === 'string') row.customer = changes.customer;
|
|
324
|
+
row.version++;
|
|
325
|
+
if ((headers.prefer ?? '').includes('return=representation')) return { status: 200, statusText: 'OK', body: this.entity(row) };
|
|
326
|
+
return { status: 204, statusText: 'No Content', headers: { ETag: `W/"${row.version}"` } };
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
private parts(body: string, boundary: string): string[] {
|
|
330
|
+
return body
|
|
331
|
+
.split(`--${boundary}`)
|
|
332
|
+
.slice(1)
|
|
333
|
+
.filter((part) => !part.startsWith('--'));
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
private request(part: string): BatchPart {
|
|
337
|
+
const [outerHead, rest] = splitOnce(part.replace(/^\r\n/, ''), '\r\n\r\n');
|
|
338
|
+
const contentId = /content-id:\s*(\S+)/i.exec(outerHead)?.[1] ?? '';
|
|
339
|
+
const [head, reqBody] = splitOnce(rest, '\r\n\r\n');
|
|
340
|
+
const lines = head.split('\r\n');
|
|
341
|
+
const [method, url] = lines[0].split(' ');
|
|
342
|
+
const headers: Record<string, string> = {};
|
|
343
|
+
for (const line of lines.slice(1)) {
|
|
344
|
+
const colon = line.indexOf(':');
|
|
345
|
+
if (colon > 0) headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
|
|
346
|
+
}
|
|
347
|
+
return { contentId, method, url, headers, body: reqBody.trim() || undefined };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
private httpPart(a: Answer, contentId: string): string {
|
|
351
|
+
const head = { ...(a.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...a.headers };
|
|
352
|
+
const lines = ['Content-Type: application/http', `Content-ID: ${contentId}`, '', `HTTP/1.1 ${a.status} ${a.statusText}`];
|
|
353
|
+
for (const [name, value] of Object.entries(head)) lines.push(`${name}: ${value}`);
|
|
354
|
+
return [...lines, '', a.body === undefined ? '' : JSON.stringify(a.body)].join('\r\n');
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
private multipart(parts: string[], boundary: string): string {
|
|
358
|
+
return parts.map((part) => `--${boundary}\r\n${part}\r\n`).join('') + `--${boundary}--\r\n`;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
private batch(body: string, contentType: string): Response {
|
|
362
|
+
const outer = this.parts(body, boundaryOf(contentType));
|
|
363
|
+
const changeset = outer.length === 1 && /multipart\/mixed/i.test(splitOnce(outer[0], '\r\n\r\n')[0]);
|
|
364
|
+
const requests = changeset ? this.parts(splitOnce(outer[0], '\r\n\r\n')[1], boundaryOf(splitOnce(outer[0], '\r\n\r\n')[0])).map((p) => this.request(p)) : outer.map((p) => this.request(p));
|
|
365
|
+
let answered: string;
|
|
366
|
+
const stopped = changeset ? requests.map((r) => this.trouble(r.method, this.rows.get(Number(/\((\d+)\)/.exec(r.url)?.[1])), r.headers)).find((a) => a !== null) : null;
|
|
367
|
+
if (stopped) {
|
|
368
|
+
// A failed change set answers once for all of its changes.
|
|
369
|
+
answered = this.multipart([this.httpPart(stopped, '1')], 'response_1');
|
|
370
|
+
} else {
|
|
371
|
+
const parts = requests.map((r) => this.httpPart(this.answer(r.method, r.url, r.headers, r.body), r.contentId));
|
|
372
|
+
answered = changeset ? this.multipart([`Content-Type: multipart/mixed; boundary=cs_1\r\n\r\n${this.multipart(parts, 'cs_1').trimEnd()}`], 'response_1') : this.multipart(parts, 'response_1');
|
|
373
|
+
}
|
|
374
|
+
return new Response(answered, { status: 200, statusText: 'OK', headers: { 'content-type': 'multipart/mixed; boundary=response_1' } });
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
## CORS
|
|
380
|
+
|
|
381
|
+
Reads carry no custom header, only `Accept: application/json`: a browser sends them without a CORS preflight, so a service that is only read needs nothing beyond `Access-Control-Allow-Origin`. Writes and `$batch` requests carry `OData-Version: 4.0`, `OData-MaxVersion: 4.0` and their content type: the browser preflights them, and the service must allow those headers and the methods used.
|
|
382
|
+
|
|
383
|
+
## API reference
|
|
384
|
+
|
|
385
|
+
`ODataAdapterOptions` extends the [HTTP options](datalayer-rest.md#requests) and the [shared adapter options](datalayer-api.md) `key`, `fields`, `locale` and `capabilities` with:
|
|
386
|
+
|
|
387
|
+
| Option | Default | Description |
|
|
388
|
+
| --- | --- | --- |
|
|
389
|
+
| `url` | — | The entity set, such as `https://host/odata/Orders`. Trailing slashes are removed, and the address up to the set's name is the service root, used for `$batch` and relative next links. |
|
|
390
|
+
| `itemUrl` | from the key | The address of one row. The default appends the key in parentheses, `url(5)`, `url('4-B')`, `url(OrderId=7,Line=2)`, the literals written by the key fields' types; a `key` given as a function needs this option. |
|
|
391
|
+
| `updateMethod` | `'PATCH'` | The method of `update`; `'PUT'` for a service that replaces the row. |
|
|
392
|
+
| `ignoreCase` | `true` | Text filters compare without case through `tolower()`, the value lowered in `locale`. A condition with `caseSensitive` compares as written either way. |
|
|
393
|
+
| `collections` | — | The fields that hold a list of values, such as `Tags`; [conditions on them](#filters) are written with `any()`. |
|
|
394
|
+
| `returnSavedRow` | `true` | Asks for the saved row back with `Prefer: return=representation` ([Writing](#writing)). |
|
|
395
|
+
| `followNextLink` | `true` | Follows `@odata.nextLink` when the service answers in pages ([Paging by the service](#paging)). |
|
|
396
|
+
| `readRow` | — | Changes each row read from the service, such as date strings into `Date` values; it runs for loads, `byKey` and saved rows. |
|
|
397
|
+
| `aggregation` | `false` | The service supports `$apply` (OData Data Aggregation): summaries and pivots are computed there ([Aggregation](#aggregation)). `true`, or an `ODataAggregationOptions` object. |
|
|
398
|
+
| `batch` | — | Saves many changes in one `$batch` request ([Writing](#writing)): `true`, or an `ODataBatchOptions` object. |
|
|
399
|
+
|
|
400
|
+
`ODataAggregationOptions`, the object form of `aggregation`:
|
|
401
|
+
|
|
402
|
+
| Option | Default | Description |
|
|
403
|
+
| --- | --- | --- |
|
|
404
|
+
| `compute` | `false` | The service takes `compute`: pivot levels with an interval are computed there (`year()`, `month()`, `day()`, `date()`, `floor()`), by the service's clock. Without it such a pivot is grouped in memory; `'dayOfWeek'` has no OData function and always is. |
|
|
405
|
+
| `conditional` | `false` | The service takes `case` in `compute` (OData 4.01): pivot members ordered by a measure in a member of the other axis are counted and paged there. Without it every member of the parent is read and ordered in memory. |
|
|
406
|
+
| `pageSize` | — | The rows one answer to `$apply` may hold: a read of every group in an order is asked for in pages of that many rows, with `$skip` and `$top`. Without it such a read is one request, and the pages the service itself cuts it into are followed. |
|
|
407
|
+
| `batch` | `false` | A pivot sends its requests, one per pair of depths of its axes, in one `$batch` request, to the `batch` option's `url` when it gives one. Without it they go one request each, all at once. |
|
|
408
|
+
|
|
409
|
+
`ODataBatchOptions`, the object form of `batch`:
|
|
410
|
+
|
|
411
|
+
| Option | Default | Description |
|
|
412
|
+
| --- | --- | --- |
|
|
413
|
+
| `url` | the service root plus `$batch` | The address the `$batch` request is posted to. |
|
|
414
|
+
| `allOrNothing` | `false` | Sends the changes as one change set: the service saves all of them or none. |
|
|
415
|
+
|
|
416
|
+
`ODataFilterOptions`, the options of `toODataFilter`:
|
|
417
|
+
|
|
418
|
+
| Option | Default | Description |
|
|
419
|
+
| --- | --- | --- |
|
|
420
|
+
| `fields` | — | The field types, which decide the literals ([Creating an OData adapter](#adapter)). |
|
|
421
|
+
| `locale` | — | The locale text values are lowered in for comparisons without case. |
|
|
422
|
+
| `ignoreCase` | `true` | Text compares without case through `tolower()`. |
|
|
423
|
+
| `collections` | — | The fields that hold a list of values; their conditions are written with `any()`. |
|
|
424
|
+
|
|
425
|
+
| Function | Description |
|
|
426
|
+
| --- | --- |
|
|
427
|
+
| `toODataFilter(filter, options?)` | Returns the filter as an OData v4 `$filter` that keeps the rows it keeps in memory, or `'true'` when it keeps every row. Throws a `TypeError` for a value its field type cannot hold, and for a condition OData cannot write. |
|
|
428
|
+
| `odataLiteral(value, type)` | Returns a value as an OData v4 literal: `'O''Brien'`, `12.5`, `true`, `2024-03-05`, a GUID without quotes. Throws a `TypeError` for a value the type cannot hold. |
|
|
429
|
+
|
|
430
|
+
## Feedback
|
|
431
|
+
|
|
432
|
+
Loading issues…
|
|
433
|
+
|
|
434
|
+
## Example files
|
|
435
|
+
|
|
436
|
+
`Inspector.tsx`
|
|
437
|
+
|
|
438
|
+
```tsx
|
|
439
|
+
import { reactive } from '@motifx/core';
|
|
440
|
+
import { data } from '@motifx-community/data';
|
|
441
|
+
import { CheckBox, DateBox, DropDown, NumberBox, Stack, TextBox } from '@motifx-community/ui';
|
|
442
|
+
import type { Customer, Product } from './orders';
|
|
443
|
+
import { ordersService } from './orders-service';
|
|
444
|
+
|
|
445
|
+
type Row = Record<string, unknown>;
|
|
446
|
+
type Line = { units: number; product: Product };
|
|
447
|
+
|
|
448
|
+
const TAGS = ['express', 'fragile', 'gift'];
|
|
449
|
+
const SORTS = ['orderedOn', 'freight', 'city', 'id'];
|
|
450
|
+
const PAGE = 4;
|
|
451
|
+
|
|
452
|
+
const customerOf = (r: Row) => (r.customer ? (r.customer as Customer).name : '');
|
|
453
|
+
const linesOf = (r: Row) => ((r.lines as Line[] | undefined) ?? []).map((l) => `${l.units} × ${l.product.name}`).join(', ');
|
|
454
|
+
|
|
455
|
+
/** Builds a query from the controls, sends it through the adapter, and shows the URL and the answer. */
|
|
456
|
+
export default function Inspector() {
|
|
457
|
+
const s = reactive({
|
|
458
|
+
city: 'ber',
|
|
459
|
+
tag: null as string | null,
|
|
460
|
+
after: null as Date | null,
|
|
461
|
+
sort: 'orderedOn',
|
|
462
|
+
desc: false,
|
|
463
|
+
page: 1 as number | null,
|
|
464
|
+
customer: false,
|
|
465
|
+
lines: false,
|
|
466
|
+
url: '',
|
|
467
|
+
total: 0,
|
|
468
|
+
rows: [] as Row[],
|
|
469
|
+
problem: '',
|
|
470
|
+
});
|
|
471
|
+
const adapter = new data.ODataAdapter<Row, number>({
|
|
472
|
+
url: 'https://host/odata/Orders',
|
|
473
|
+
key: 'id',
|
|
474
|
+
locale: 'en-US',
|
|
475
|
+
fields: { orderedOn: 'date' },
|
|
476
|
+
collections: ['tags'],
|
|
477
|
+
fetch: ordersService((url) => (s.url = decodeURIComponent(url))),
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
const send = async () => {
|
|
481
|
+
try {
|
|
482
|
+
const result = await adapter.load({
|
|
483
|
+
filter: data.and(
|
|
484
|
+
data.where('city', 'contains', s.city),
|
|
485
|
+
s.tag === null ? null : data.where('tags', '=', s.tag),
|
|
486
|
+
s.after === null ? null : data.where('orderedOn', '>=', s.after),
|
|
487
|
+
),
|
|
488
|
+
sort: [{ field: s.sort, dir: s.desc ? 'desc' : 'asc' }],
|
|
489
|
+
skip: ((s.page ?? 1) - 1) * PAGE,
|
|
490
|
+
take: PAGE,
|
|
491
|
+
count: true,
|
|
492
|
+
expand: [...(s.customer ? ['customer'] : []), ...(s.lines ? ['lines.product'] : [])],
|
|
493
|
+
});
|
|
494
|
+
s.rows = result.rows;
|
|
495
|
+
s.total = result.total ?? 0;
|
|
496
|
+
s.problem = '';
|
|
497
|
+
} catch (error) {
|
|
498
|
+
s.rows = [];
|
|
499
|
+
s.total = 0;
|
|
500
|
+
s.problem = (error as Error).message;
|
|
501
|
+
}
|
|
502
|
+
};
|
|
503
|
+
void send();
|
|
504
|
+
|
|
505
|
+
return (
|
|
506
|
+
<>
|
|
507
|
+
<Stack orientation="horizontal" wrap align="end">
|
|
508
|
+
<TextBox label="City contains" clearButton x-model={() => s.city} onValueChanged={send} style="inline-size: 9rem" />
|
|
509
|
+
<DropDown label="Has the tag" items={TAGS} clearButton placeholder="any" x-model={() => s.tag} onValueChanged={send} style="inline-size: 9rem" />
|
|
510
|
+
<DateBox label="Ordered on or after" clearButton x-model={() => s.after} onValueChanged={send} style="inline-size: 11rem" />
|
|
511
|
+
<DropDown label="Sort by" items={SORTS} x-model={() => s.sort} onValueChanged={send} style="inline-size: 8.5rem" />
|
|
512
|
+
<NumberBox label="Page" min={1} max={9} x-model={() => s.page} onValueChanged={send} style="inline-size: 6rem" />
|
|
513
|
+
<CheckBox label="Descending" x-model={() => s.desc} onValueChanged={send} />
|
|
514
|
+
<CheckBox label="Expand customer" x-model={() => s.customer} onValueChanged={send} />
|
|
515
|
+
<CheckBox label="Expand lines.product" x-model={() => s.lines} onValueChanged={send} />
|
|
516
|
+
</Stack>
|
|
517
|
+
<pre class="od-url" style="white-space: pre-wrap; overflow-wrap: anywhere; inline-size: 100%; box-sizing: border-box">{() => s.url}</pre>
|
|
518
|
+
<output class="od-problem" style="color: var(--mx-color-danger-fg)" x-wait={() => !s.problem}>
|
|
519
|
+
{() => s.problem}
|
|
520
|
+
</output>
|
|
521
|
+
<div class="table-scroll" style="inline-size: 100%">
|
|
522
|
+
<table class="token-table">
|
|
523
|
+
<thead>
|
|
524
|
+
<tr>
|
|
525
|
+
<th>id</th>
|
|
526
|
+
<th>city</th>
|
|
527
|
+
<th>orderedOn</th>
|
|
528
|
+
<th>freight</th>
|
|
529
|
+
<th>tags</th>
|
|
530
|
+
<th>customer</th>
|
|
531
|
+
<th>lines</th>
|
|
532
|
+
</tr>
|
|
533
|
+
</thead>
|
|
534
|
+
<tbody>
|
|
535
|
+
{() =>
|
|
536
|
+
s.rows.map((r) => (
|
|
537
|
+
<tr key={r.id as number}>
|
|
538
|
+
<td>{String(r.id)}</td>
|
|
539
|
+
<td>{String(r.city)}</td>
|
|
540
|
+
<td>{String(r.orderedOn)}</td>
|
|
541
|
+
<td>{String(r.freight)}</td>
|
|
542
|
+
<td>{(r.tags as string[]).join(', ')}</td>
|
|
543
|
+
<td>{customerOf(r)}</td>
|
|
544
|
+
<td>{linesOf(r)}</td>
|
|
545
|
+
</tr>
|
|
546
|
+
))
|
|
547
|
+
}
|
|
548
|
+
</tbody>
|
|
549
|
+
</table>
|
|
550
|
+
</div>
|
|
551
|
+
<output class="od-total">{() => `@odata.count: ${s.total} matching rows · the page shows ${s.rows.length}`}</output>
|
|
552
|
+
</>
|
|
553
|
+
);
|
|
554
|
+
}
|
|
555
|
+
```
|
|
556
|
+
|
|
557
|
+
`orders-service.ts`
|
|
558
|
+
|
|
559
|
+
```tsx
|
|
560
|
+
import { customers, orderLines, orders, products, type Order } from './orders';
|
|
561
|
+
|
|
562
|
+
// An OData v4 service over the orders, running in the page. It reads only the URL it is given, so the
|
|
563
|
+
// answer can never contradict the request: the small $filter subset the inspector writes is parsed and
|
|
564
|
+
// evaluated here, and a condition outside it answers 400.
|
|
565
|
+
|
|
566
|
+
/** Splits a `$filter` on its top-level ` and `, leaving quoted text alone. */
|
|
567
|
+
function conditions(filter: string): string[] {
|
|
568
|
+
const out: string[] = [];
|
|
569
|
+
let part = '';
|
|
570
|
+
let quoted = false;
|
|
571
|
+
for (let i = 0; i < filter.length; i++) {
|
|
572
|
+
if (filter[i] === "'") quoted = !quoted;
|
|
573
|
+
if (!quoted && filter.startsWith(' and ', i)) {
|
|
574
|
+
out.push(part);
|
|
575
|
+
part = '';
|
|
576
|
+
i += 4;
|
|
577
|
+
continue;
|
|
578
|
+
}
|
|
579
|
+
part += filter[i];
|
|
580
|
+
}
|
|
581
|
+
return [...out, part];
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
const unquote = (text: string) => text.replace(/''/g, "'");
|
|
585
|
+
|
|
586
|
+
function test(condition: string): (o: Order) => boolean {
|
|
587
|
+
let m = /^contains\(tolower\(city\),'(.*)'\)$/.exec(condition);
|
|
588
|
+
if (m) {
|
|
589
|
+
const value = unquote(m[1]);
|
|
590
|
+
return (o) => o.city.toLowerCase().includes(value);
|
|
591
|
+
}
|
|
592
|
+
m = /^tags\/any\(x: tolower\(x\) eq '(.*)'\)$/.exec(condition);
|
|
593
|
+
if (m) {
|
|
594
|
+
const value = unquote(m[1]);
|
|
595
|
+
return (o) => o.tags.some((tag) => tag.toLowerCase() === value);
|
|
596
|
+
}
|
|
597
|
+
m = /^orderedOn ge (\d{4}-\d{2}-\d{2})$/.exec(condition);
|
|
598
|
+
if (m) {
|
|
599
|
+
const day = m[1];
|
|
600
|
+
return (o) => o.orderedOn >= day;
|
|
601
|
+
}
|
|
602
|
+
throw new Error(`The sample service does not read "${condition}".`);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
function sorted(rows: Order[], orderby: string): Order[] {
|
|
606
|
+
const m = /^(\w+)( desc)?$/.exec(orderby);
|
|
607
|
+
if (!m) throw new Error(`The sample service does not read "$orderby=${orderby}".`);
|
|
608
|
+
const field = m[1] as keyof Order;
|
|
609
|
+
const sign = m[2] ? -1 : 1;
|
|
610
|
+
return [...rows].sort((a, b) => {
|
|
611
|
+
const [x, y] = [a[field], b[field]];
|
|
612
|
+
return sign * (typeof x === 'number' && typeof y === 'number' ? x - y : String(x) < String(y) ? -1 : x === y ? 0 : 1);
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
function expanded(order: Order, expand: string): Record<string, unknown> {
|
|
617
|
+
const row: Record<string, unknown> = { ...order };
|
|
618
|
+
for (const path of expand ? expand.split(',') : []) {
|
|
619
|
+
if (path === 'customer') {
|
|
620
|
+
row.customer = customers.find((c) => c.id === order.customerId);
|
|
621
|
+
} else if (path === 'lines' || path === 'lines($expand=product)') {
|
|
622
|
+
row.lines = orderLines
|
|
623
|
+
.filter((line) => line.order === order.id)
|
|
624
|
+
.map((line) => (path === 'lines' ? { ...line } : { ...line, product: products.find((p) => p.id === line.product) }));
|
|
625
|
+
} else {
|
|
626
|
+
throw new Error(`The sample service does not read "$expand=${path}".`);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
return row;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
|
|
633
|
+
|
|
634
|
+
/** The `fetch` the adapter is given: `asked` sees every URL before it is answered. */
|
|
635
|
+
export function ordersService(asked: (url: string) => void) {
|
|
636
|
+
return async (input: string, _init: RequestInit): Promise<Response> => {
|
|
637
|
+
asked(input);
|
|
638
|
+
try {
|
|
639
|
+
const query = new URL(input).searchParams;
|
|
640
|
+
const filter = query.get('$filter');
|
|
641
|
+
let rows = filter ? orders.filter((o) => conditions(filter).every((c) => test(c)(o))) : [...orders];
|
|
642
|
+
const orderby = query.get('$orderby');
|
|
643
|
+
if (orderby) rows = sorted(rows, orderby);
|
|
644
|
+
const total = rows.length;
|
|
645
|
+
const skip = Number(query.get('$skip') ?? 0);
|
|
646
|
+
const top = query.get('$top');
|
|
647
|
+
rows = rows.slice(skip, top === null ? undefined : skip + Number(top));
|
|
648
|
+
const expand = query.get('$expand') ?? '';
|
|
649
|
+
return json({
|
|
650
|
+
'@odata.context': 'https://host/odata/$metadata#Orders',
|
|
651
|
+
...(query.get('$count') === 'true' ? { '@odata.count': total } : {}),
|
|
652
|
+
value: rows.map((o) => expanded(o, expand)),
|
|
653
|
+
});
|
|
654
|
+
} catch (error) {
|
|
655
|
+
return json({ error: { code: 'NotSupported', message: (error as Error).message } }, 400);
|
|
656
|
+
}
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
```
|
|
660
|
+
|
|
661
|
+
`orders.ts`
|
|
662
|
+
|
|
663
|
+
```tsx
|
|
664
|
+
// Invented rows behind the in-page OData service: orders with a customer, lines with a product, and tags.
|
|
665
|
+
export interface Customer {
|
|
666
|
+
id: number;
|
|
667
|
+
name: string;
|
|
668
|
+
city: string;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
export interface Product {
|
|
672
|
+
id: number;
|
|
673
|
+
name: string;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
export interface OrderLine {
|
|
677
|
+
id: number;
|
|
678
|
+
order: number;
|
|
679
|
+
product: number;
|
|
680
|
+
units: number;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
export interface Order {
|
|
684
|
+
id: number;
|
|
685
|
+
customerId: number;
|
|
686
|
+
city: string;
|
|
687
|
+
/** A calendar day, as an OData date property answers. */
|
|
688
|
+
orderedOn: string;
|
|
689
|
+
freight: number;
|
|
690
|
+
tags: string[];
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
export const customers: Customer[] = [
|
|
694
|
+
{ id: 1, name: 'Elif Demir', city: 'Oslo' },
|
|
695
|
+
{ id: 2, name: 'Can Yılmaz', city: 'Berlin' },
|
|
696
|
+
{ id: 3, name: 'Zeynep Kaya', city: 'İzmir' },
|
|
697
|
+
{ id: 4, name: 'Mert Şahin', city: 'Lisbon' },
|
|
698
|
+
];
|
|
699
|
+
|
|
700
|
+
export const products: Product[] = [
|
|
701
|
+
{ id: 1, name: 'Walnut desk' },
|
|
702
|
+
{ id: 2, name: 'Brass lamp' },
|
|
703
|
+
{ id: 3, name: 'Wool rug' },
|
|
704
|
+
{ id: 4, name: 'Oak shelf' },
|
|
705
|
+
{ id: 5, name: 'Glass vase' },
|
|
706
|
+
];
|
|
707
|
+
|
|
708
|
+
export const orders: Order[] = [
|
|
709
|
+
{ id: 1, customerId: 1, city: 'Oslo', orderedOn: '2026-01-12', freight: 42.5, tags: ['express'] },
|
|
710
|
+
{ id: 2, customerId: 2, city: 'Berlin', orderedOn: '2026-02-03', freight: 18, tags: ['gift'] },
|
|
711
|
+
{ id: 3, customerId: 3, city: 'İzmir', orderedOn: '2026-02-21', freight: 96.2, tags: ['fragile', 'express'] },
|
|
712
|
+
{ id: 4, customerId: 1, city: 'Bergen', orderedOn: '2026-03-15', freight: 7.75, tags: [] },
|
|
713
|
+
{ id: 5, customerId: 4, city: 'Lisbon', orderedOn: '2026-04-02', freight: 130, tags: ['fragile'] },
|
|
714
|
+
{ id: 6, customerId: 2, city: 'Hamburg', orderedOn: '2026-05-19', freight: 55.4, tags: ['express', 'gift'] },
|
|
715
|
+
{ id: 7, customerId: 3, city: 'Ankara', orderedOn: '2026-06-08', freight: 23.9, tags: [] },
|
|
716
|
+
{ id: 8, customerId: 1, city: 'Oslo', orderedOn: '2026-07-27', freight: 61, tags: ['gift'] },
|
|
717
|
+
{ id: 9, customerId: 4, city: 'Porto', orderedOn: '2026-08-14', freight: 12.3, tags: ['express'] },
|
|
718
|
+
{ id: 10, customerId: 2, city: 'Berlin', orderedOn: '2026-09-05', freight: 88.8, tags: ['fragile'] },
|
|
719
|
+
{ id: 11, customerId: 3, city: 'İzmir', orderedOn: '2026-10-22', freight: 34, tags: ['gift', 'express'] },
|
|
720
|
+
{ id: 12, customerId: 1, city: 'Bodø', orderedOn: '2026-11-10', freight: 150.25, tags: [] },
|
|
721
|
+
];
|
|
722
|
+
|
|
723
|
+
export const orderLines: OrderLine[] = [
|
|
724
|
+
{ id: 1, order: 1, product: 1, units: 2 },
|
|
725
|
+
{ id: 2, order: 1, product: 3, units: 1 },
|
|
726
|
+
{ id: 3, order: 2, product: 2, units: 4 },
|
|
727
|
+
{ id: 4, order: 3, product: 5, units: 6 },
|
|
728
|
+
{ id: 5, order: 4, product: 4, units: 1 },
|
|
729
|
+
{ id: 6, order: 5, product: 5, units: 12 },
|
|
730
|
+
{ id: 7, order: 6, product: 2, units: 2 },
|
|
731
|
+
{ id: 8, order: 6, product: 1, units: 1 },
|
|
732
|
+
{ id: 9, order: 7, product: 3, units: 3 },
|
|
733
|
+
{ id: 10, order: 8, product: 4, units: 5 },
|
|
734
|
+
{ id: 11, order: 9, product: 2, units: 1 },
|
|
735
|
+
{ id: 12, order: 10, product: 5, units: 8 },
|
|
736
|
+
{ id: 13, order: 11, product: 1, units: 1 },
|
|
737
|
+
{ id: 14, order: 12, product: 3, units: 2 },
|
|
738
|
+
];
|
|
739
|
+
```
|
|
740
|
+
|
|
741
|
+
`Writing.tsx`
|
|
742
|
+
|
|
743
|
+
```tsx
|
|
744
|
+
import { reactive } from '@motifx/core';
|
|
745
|
+
import { data } from '@motifx-community/data';
|
|
746
|
+
import { Button, CheckBox, NumberBox, Stack } from '@motifx-community/ui';
|
|
747
|
+
import { WriteService } from './write-service';
|
|
748
|
+
|
|
749
|
+
type Row = Record<string, unknown>;
|
|
750
|
+
|
|
751
|
+
// The headers worth showing, as the adapter writes them.
|
|
752
|
+
const SHOWN = ['If-Match', 'Prefer', 'OData-Version', 'OData-MaxVersion', 'Content-Type'];
|
|
753
|
+
const PRE = 'white-space: pre-wrap; overflow-wrap: anywhere; inline-size: 100%; box-sizing: border-box; max-block-size: 16rem';
|
|
754
|
+
|
|
755
|
+
/** An update with its If-Match, a conflict becoming MJD205, and a save in one $batch. */
|
|
756
|
+
export default function Writing() {
|
|
757
|
+
const s = reactive({
|
|
758
|
+
freight1: 50 as number | null,
|
|
759
|
+
freight2: 25 as number | null,
|
|
760
|
+
allOrNothing: true,
|
|
761
|
+
row1: {} as Row,
|
|
762
|
+
row2: {} as Row,
|
|
763
|
+
request: '',
|
|
764
|
+
outcome: 'Nothing saved yet.',
|
|
765
|
+
});
|
|
766
|
+
const service = new WriteService((method, url, headers, body) => {
|
|
767
|
+
const lines = [`${method} ${url}`];
|
|
768
|
+
for (const name of SHOWN) {
|
|
769
|
+
const value = headers.get(name);
|
|
770
|
+
if (value) lines.push(`${name}: ${value}`);
|
|
771
|
+
}
|
|
772
|
+
if (body) lines.push('', body);
|
|
773
|
+
s.request = lines.join('\n');
|
|
774
|
+
});
|
|
775
|
+
s.row1 = service.row(1);
|
|
776
|
+
s.row2 = service.row(2);
|
|
777
|
+
|
|
778
|
+
const options = { url: 'https://host/odata/Orders', key: 'id', fetch: service.fetch };
|
|
779
|
+
const adapter = new data.ODataAdapter<Row, number>(options);
|
|
780
|
+
const batchedEach = new data.ODataAdapter<Row, number>({ ...options, batch: true });
|
|
781
|
+
const batchedAll = new data.ODataAdapter<Row, number>({ ...options, batch: { allOrNothing: true } });
|
|
782
|
+
|
|
783
|
+
const failed = (error: unknown) => {
|
|
784
|
+
const e = error as data.DataError;
|
|
785
|
+
s.outcome = `${e.code} (${e.kind}): ${e.plainMessage}`;
|
|
786
|
+
};
|
|
787
|
+
const save = async () => {
|
|
788
|
+
try {
|
|
789
|
+
const saved = await adapter.update(1, { freight: s.freight1 ?? 0 }, { original: s.row1 });
|
|
790
|
+
s.row1 = { ...s.row1, ...saved };
|
|
791
|
+
s.outcome = `Saved: the etag of order 1 is now ${String(s.row1['@odata.etag'])}.`;
|
|
792
|
+
} catch (error) {
|
|
793
|
+
failed(error);
|
|
794
|
+
}
|
|
795
|
+
};
|
|
796
|
+
const withoutOriginal = async () => {
|
|
797
|
+
try {
|
|
798
|
+
await adapter.update(1, { freight: s.freight1 ?? 0 }, {});
|
|
799
|
+
s.outcome = 'Saved without a version.';
|
|
800
|
+
} catch (error) {
|
|
801
|
+
failed(error);
|
|
802
|
+
}
|
|
803
|
+
};
|
|
804
|
+
const read = async () => {
|
|
805
|
+
s.row1 = (await adapter.byKey(1)) ?? s.row1;
|
|
806
|
+
s.outcome = 'Order 1 read again: its etag is fresh.';
|
|
807
|
+
};
|
|
808
|
+
const saveBatch = async () => {
|
|
809
|
+
try {
|
|
810
|
+
const outcomes = await (s.allOrNothing ? batchedAll : batchedEach).save([
|
|
811
|
+
{ type: 'update', key: 1, data: { freight: s.freight1 ?? 0 }, original: s.row1 },
|
|
812
|
+
{ type: 'update', key: 2, data: { freight: s.freight2 ?? 0 }, original: s.row2 },
|
|
813
|
+
]);
|
|
814
|
+
outcomes.forEach((outcome, i) => {
|
|
815
|
+
if (!outcome.ok || !outcome.row) return;
|
|
816
|
+
if (i === 0) s.row1 = { ...s.row1, ...outcome.row };
|
|
817
|
+
else s.row2 = { ...s.row2, ...outcome.row };
|
|
818
|
+
});
|
|
819
|
+
s.outcome = outcomes.map((o, i) => `order ${i + 1}: ${o.ok ? 'saved' : `${o.error.code}: ${o.error.plainMessage}`}`).join(' | ');
|
|
820
|
+
} catch (error) {
|
|
821
|
+
failed(error);
|
|
822
|
+
}
|
|
823
|
+
};
|
|
824
|
+
|
|
825
|
+
return (
|
|
826
|
+
<>
|
|
827
|
+
<Stack orientation="horizontal" wrap align="end">
|
|
828
|
+
<NumberBox label="Freight of order 1" min={0} x-model={() => s.freight1} style="inline-size: 9rem" />
|
|
829
|
+
<Button text="Save the change" onclick={save} />
|
|
830
|
+
<Button
|
|
831
|
+
text="Change it elsewhere"
|
|
832
|
+
variant="outline"
|
|
833
|
+
onclick={() => {
|
|
834
|
+
service.changeElsewhere(1);
|
|
835
|
+
s.outcome = 'Another session saved order 1: the service holds a newer version now.';
|
|
836
|
+
}}
|
|
837
|
+
/>
|
|
838
|
+
<Button text="Read it again" variant="outline" onclick={read} />
|
|
839
|
+
<Button text="Save without original" variant="outline" onclick={withoutOriginal} />
|
|
840
|
+
</Stack>
|
|
841
|
+
<Stack orientation="horizontal" wrap align="end">
|
|
842
|
+
<NumberBox label="Freight of order 2" min={0} x-model={() => s.freight2} style="inline-size: 9rem" />
|
|
843
|
+
<CheckBox label="allOrNothing: one change set" x-model={() => s.allOrNothing} />
|
|
844
|
+
<Button text="Save both in one $batch" onclick={saveBatch} />
|
|
845
|
+
</Stack>
|
|
846
|
+
<output class="od-row1">{() => `order 1 as read: ${JSON.stringify(s.row1)}`}</output>
|
|
847
|
+
<output class="od-row2">{() => `order 2 as read: ${JSON.stringify(s.row2)}`}</output>
|
|
848
|
+
<output class="od-outcome">{() => s.outcome}</output>
|
|
849
|
+
<pre class="od-request" style={PRE}>{() => (s.request ? s.request : 'No request sent yet.')}</pre>
|
|
850
|
+
</>
|
|
851
|
+
);
|
|
852
|
+
}
|
|
853
|
+
```
|
|
854
|
+
|
|
855
|
+
`write-service.ts`
|
|
856
|
+
|
|
857
|
+
```tsx
|
|
858
|
+
// An OData v4 service with two orders, running in the page: writes save only over the version named in
|
|
859
|
+
// If-Match, and a $batch body is read part by part, a change set as one unit.
|
|
860
|
+
|
|
861
|
+
interface Stored {
|
|
862
|
+
id: number;
|
|
863
|
+
customer: string;
|
|
864
|
+
freight: number;
|
|
865
|
+
version: number;
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
interface Answer {
|
|
869
|
+
status: number;
|
|
870
|
+
statusText: string;
|
|
871
|
+
headers?: Record<string, string>;
|
|
872
|
+
body?: unknown;
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
interface BatchPart {
|
|
876
|
+
contentId: string;
|
|
877
|
+
method: string;
|
|
878
|
+
url: string;
|
|
879
|
+
headers: Record<string, string>;
|
|
880
|
+
body?: string;
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
const fail = (status: number, statusText: string, message: string): Answer => ({ status, statusText, body: { error: { code: '', message } } });
|
|
884
|
+
const splitOnce = (text: string, mark: string): [string, string] => {
|
|
885
|
+
const at = text.indexOf(mark);
|
|
886
|
+
return at < 0 ? [text, ''] : [text.slice(0, at), text.slice(at + mark.length)];
|
|
887
|
+
};
|
|
888
|
+
const boundaryOf = (contentType: string) => /boundary="?([^";\s]+)"?/i.exec(contentType)?.[1] ?? '';
|
|
889
|
+
|
|
890
|
+
export class WriteService {
|
|
891
|
+
private readonly rows = new Map<number, Stored>([
|
|
892
|
+
[1, { id: 1, customer: 'Elif Demir', freight: 42.5, version: 1 }],
|
|
893
|
+
[2, { id: 2, customer: 'Can Yılmaz', freight: 18, version: 1 }],
|
|
894
|
+
]);
|
|
895
|
+
|
|
896
|
+
constructor(private readonly asked: (method: string, url: string, headers: Headers, body: string | undefined) => void) {}
|
|
897
|
+
|
|
898
|
+
/** Another session saves the row: its version moves on. */
|
|
899
|
+
changeElsewhere(id: number): void {
|
|
900
|
+
const row = this.rows.get(id)!;
|
|
901
|
+
row.freight = Math.round((row.freight + 2.5) * 100) / 100;
|
|
902
|
+
row.version++;
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
row(id: number): Record<string, unknown> {
|
|
906
|
+
return this.entity(this.rows.get(id)!);
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
readonly fetch = async (input: string, init: RequestInit): Promise<Response> => {
|
|
910
|
+
const headers = new Headers(init.headers);
|
|
911
|
+
const body = init.body === undefined || init.body === null ? undefined : String(init.body);
|
|
912
|
+
this.asked(init.method ?? 'GET', input, headers, body);
|
|
913
|
+
if (new URL(input).pathname.endsWith('/$batch')) return this.batch(body ?? '', headers.get('content-type') ?? '');
|
|
914
|
+
const record: Record<string, string> = {};
|
|
915
|
+
headers.forEach((value, name) => (record[name] = value));
|
|
916
|
+
const a = this.answer(init.method ?? 'GET', input, record, body);
|
|
917
|
+
const head = { ...(a.body === undefined ? {} : { 'content-type': 'application/json' }), ...a.headers };
|
|
918
|
+
return new Response(a.body === undefined ? null : JSON.stringify(a.body), { status: a.status, statusText: a.statusText, headers: head });
|
|
919
|
+
};
|
|
920
|
+
|
|
921
|
+
private entity(row: Stored): Record<string, unknown> {
|
|
922
|
+
return { '@odata.etag': `W/"${row.version}"`, id: row.id, customer: row.customer, freight: row.freight };
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
// What would stop this request; null when it saves.
|
|
926
|
+
private trouble(method: string, row: Stored | undefined, headers: Record<string, string>): Answer | null {
|
|
927
|
+
if (!row) return fail(404, 'Not Found', 'No order with this key.');
|
|
928
|
+
if (method !== 'PATCH' && method !== 'GET') return fail(405, 'Method Not Allowed', `This service does not take ${method}.`);
|
|
929
|
+
if (method === 'GET') return null;
|
|
930
|
+
const ifMatch = headers['if-match'];
|
|
931
|
+
if (!ifMatch) return fail(428, 'Precondition Required', 'This service saves only over a version: send If-Match.');
|
|
932
|
+
if (ifMatch !== `W/"${row.version}"`) return fail(412, 'Precondition Failed', 'The order was changed by someone else.');
|
|
933
|
+
return null;
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
private answer(method: string, url: string, headers: Record<string, string>, body: string | undefined): Answer {
|
|
937
|
+
const id = Number(/\((\d+)\)/.exec(new URL(url).pathname)?.[1]);
|
|
938
|
+
const row = this.rows.get(id);
|
|
939
|
+
const stopped = this.trouble(method, row, headers);
|
|
940
|
+
if (stopped || !row) return stopped ?? fail(404, 'Not Found', 'No order with this key.');
|
|
941
|
+
if (method === 'GET') return { status: 200, statusText: 'OK', body: this.entity(row) };
|
|
942
|
+
const changes = JSON.parse(body ?? '{}') as Partial<Stored>;
|
|
943
|
+
if (typeof changes.freight === 'number') row.freight = changes.freight;
|
|
944
|
+
if (typeof changes.customer === 'string') row.customer = changes.customer;
|
|
945
|
+
row.version++;
|
|
946
|
+
if ((headers.prefer ?? '').includes('return=representation')) return { status: 200, statusText: 'OK', body: this.entity(row) };
|
|
947
|
+
return { status: 204, statusText: 'No Content', headers: { ETag: `W/"${row.version}"` } };
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
private parts(body: string, boundary: string): string[] {
|
|
951
|
+
return body
|
|
952
|
+
.split(`--${boundary}`)
|
|
953
|
+
.slice(1)
|
|
954
|
+
.filter((part) => !part.startsWith('--'));
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
private request(part: string): BatchPart {
|
|
958
|
+
const [outerHead, rest] = splitOnce(part.replace(/^\r\n/, ''), '\r\n\r\n');
|
|
959
|
+
const contentId = /content-id:\s*(\S+)/i.exec(outerHead)?.[1] ?? '';
|
|
960
|
+
const [head, reqBody] = splitOnce(rest, '\r\n\r\n');
|
|
961
|
+
const lines = head.split('\r\n');
|
|
962
|
+
const [method, url] = lines[0].split(' ');
|
|
963
|
+
const headers: Record<string, string> = {};
|
|
964
|
+
for (const line of lines.slice(1)) {
|
|
965
|
+
const colon = line.indexOf(':');
|
|
966
|
+
if (colon > 0) headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
|
|
967
|
+
}
|
|
968
|
+
return { contentId, method, url, headers, body: reqBody.trim() || undefined };
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
private httpPart(a: Answer, contentId: string): string {
|
|
972
|
+
const head = { ...(a.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...a.headers };
|
|
973
|
+
const lines = ['Content-Type: application/http', `Content-ID: ${contentId}`, '', `HTTP/1.1 ${a.status} ${a.statusText}`];
|
|
974
|
+
for (const [name, value] of Object.entries(head)) lines.push(`${name}: ${value}`);
|
|
975
|
+
return [...lines, '', a.body === undefined ? '' : JSON.stringify(a.body)].join('\r\n');
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
private multipart(parts: string[], boundary: string): string {
|
|
979
|
+
return parts.map((part) => `--${boundary}\r\n${part}\r\n`).join('') + `--${boundary}--\r\n`;
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
private batch(body: string, contentType: string): Response {
|
|
983
|
+
const outer = this.parts(body, boundaryOf(contentType));
|
|
984
|
+
const changeset = outer.length === 1 && /multipart\/mixed/i.test(splitOnce(outer[0], '\r\n\r\n')[0]);
|
|
985
|
+
const requests = changeset ? this.parts(splitOnce(outer[0], '\r\n\r\n')[1], boundaryOf(splitOnce(outer[0], '\r\n\r\n')[0])).map((p) => this.request(p)) : outer.map((p) => this.request(p));
|
|
986
|
+
let answered: string;
|
|
987
|
+
const stopped = changeset ? requests.map((r) => this.trouble(r.method, this.rows.get(Number(/\((\d+)\)/.exec(r.url)?.[1])), r.headers)).find((a) => a !== null) : null;
|
|
988
|
+
if (stopped) {
|
|
989
|
+
// A failed change set answers once for all of its changes.
|
|
990
|
+
answered = this.multipart([this.httpPart(stopped, '1')], 'response_1');
|
|
991
|
+
} else {
|
|
992
|
+
const parts = requests.map((r) => this.httpPart(this.answer(r.method, r.url, r.headers, r.body), r.contentId));
|
|
993
|
+
answered = changeset ? this.multipart([`Content-Type: multipart/mixed; boundary=cs_1\r\n\r\n${this.multipart(parts, 'cs_1').trimEnd()}`], 'response_1') : this.multipart(parts, 'response_1');
|
|
994
|
+
}
|
|
995
|
+
return new Response(answered, { status: 200, statusText: 'OK', headers: { 'content-type': 'multipart/mixed; boundary=response_1' } });
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
```
|