M8-S2 — A new field type in the engine
Section titled “M8-S2 — A new field type in the engine”| Module | M8 — Extend the engine from source (source strand) |
| After this session you can | Add a field type end to end: its value in the shared contract, its caster, its downstream touch-points and its tests, in a tenant-safe way. |
| Time | 74 min with a facilitator · about 74 min on your own |
| Before you start | M8-S1 done: your source workbench runs and its tests are green. A local branch feat/meter-reading in each of the three code bases. M2-S3 (the wire contract) and M3-S1 (the expression engine). |
| Go deeper | How to extend the platform: add a field type · Value casters · Entity model: stored value shapes |
◆ Orientation (1 min) — A new kind of value
Section titled “◆ Orientation (1 min) — A new kind of value”Larkspur’s planners want to record meter readings on assets and work orders: a pump’s vibration in mm/s, a compressor’s discharge pressure in bar. Today a builder would use a Number field and type the unit into the field’s name, so “4.2” and “4.2 mm/s” and “4,2” all end up somewhere, and nothing checks them. You will give the platform a Meter reading field type: a value with its unit, normalised on every save, that every builder in every tenant can add to any entity.
This session is the engine half: the value in the shared contract, the caster that normalises it, the expression engine’s rule for it, the tests, and the list of everything downstream that must know the type exists. M8-S3 gives it a web control; M8-S4 takes it to the phone and proves the result is no-code for builders.
▤ Concept (9 min) — A field type is a contract in three places
Section titled “▤ Concept (9 min) — A field type is a contract in three places”What a field type is, inside
Section titled “What a field type is, inside”From the builder’s side, a field type is a choice in the designer’s palette. Inside, it is three things that must agree:
flowchart TB
subgraph C["1 The value contract"]
E["Data-type value<br/>same number in services,<br/>web and mobile"]
S["Stored shape<br/>value and unit"]
end
subgraph SV["2 The services"]
CA["Caster: normalises on save"]
EX["Expression rule:<br/>checks calculated results"]
DN["Downstream: queries,<br/>statistics, search, export"]
end
subgraph UI["3 The controls"]
W["Web edit and view control<br/>(M8-S3)"]
M["Mobile component<br/>or declared fallback (M8-S4)"]
end
E --> CA
E --> EX
S --> CA
S --> W
S --> M
CA --> DN
What to notice: the value contract is at the top because everything else depends on it. The data-type number and the stored shape are read by every service and both front ends; once records exist, neither can change without a migration.
The platform already discriminates some field kinds by data type plus edit component rather than by data type alone. A category, for example, is stored with the JSON data type and shown by the category component. So the first design question is real: could Meter reading be a new control over the existing JSON or object data type, with no change to the services at all?
| New control over an existing type | New data type | |
|---|---|---|
| Code bases changed | Web and mobile | Services, web and mobile |
| Normalisation on save | None: the JSON caster passes any object through unchanged | Your caster normalises every save, whatever the client |
| Calculated fields | Results of the object types are returned unchecked | You add a rule, so a wrong result is refused |
| What the designer and API say the field is | “JSON”, so other tools treat it as free-form data | “Meter reading”, so tools, exports and reviews can recognise it |
| Upgrade cost | Lower | Higher: three code bases, carried upstream |
What to notice: the control-only option is cheaper but leaves the server unable to tell a reading from any other object. Imports, the API and automations write values without any control in between, so a check that lives only in a control is a check most writers skip.
Larkspur’s need is a value that is right whoever writes it: the sensor feed, an import, an automation, a technician. That decides it: a new data type, so the server normalises every write. Record this as the session’s design decision; you will defend it in your standard (M10) and your capstone.
The value contract
Section titled “The value contract”The data-type value. Append MeterReading to the data-type enum in the shared package, with an
explicit number one above the newest member (on the 1.10 line the newest is SVGIcon, so the new
value is 15; check your checkout before you choose). Then re-declare the same member with the same
number in the web front end’s shared types and in the mobile domain package. Field definitions store
this number, so it is a wire contract: never reuse a number, never renumber a member, and never add it
in one code base alone. A front end that receives a number it does not know cannot render the field,
and fails quietly rather than loudly.
The stored shape. Decide the shape now, because stored records will hold it: an object with a
numeric value and a unit text, { "value": 4.2, "unit": "mm/s" }. A unit is stored with each
value, not only on the field, so that a reading keeps its meaning if a builder later changes the
field’s default unit. Changing this shape after release would need a migration of every stored record
(you saw migrations in M2-S4).
The caster: normalise, and refuse what you cannot read
Section titled “The caster: normalise, and refuse what you cannot read”A caster runs on every save, before the record is stored, and turns whatever the writer sent into
the stored shape. It is found by the booter convention from M8-S1: a file in the data service’s
casters folder whose class has static castType = DataTypeEnum.MeterReading.
Casters coerce silently: the save path does not validate a field’s type separately, so whatever
the caster returns is stored. You saw the consequence in M8-S1: the Number caster stores NaN for
garbage. Your caster must do better, on purpose:
- accept a number (
71becomes{value: 71, unit: null}), an object with a value and a unit, or a text such as"6.5 bar"; - turn anything it cannot read as a finite number into
null, never intoNaN; - trim units, and store a missing unit as
nullrather than an empty text.
Calculated results: the expression rule
Section titled “Calculated results: the expression rule”The expression engine checks a calculated field’s result against the field’s data type before it is
stored, with one rule per type; a type with no rule is returned unchecked. Add a rule for
MeterReading: the result must be an object with a finite numeric value. Without it, a builder’s
formula that returns a plain number, or a text, would be stored as a reading.
The range check: where it can and cannot live
Section titled “The range check: where it can and cannot live”Planners want a range per field: vibration between 0 and 50 mm/s. The range is a field option the builder sets in the designer, so it belongs to the field’s configuration, not to the type. A caster receives only the value, never the field’s options, so it cannot apply a per-field range. The web control (M8-S3) and the mobile component (M8-S4) can, because they receive the field. On the server, a per-field range could only be enforced by an entity validator, which is bound per entity and so is not general.
Record the decision explicitly: the server guarantees a well-formed reading; the per-field range is enforced by the controls; and note what that means for writers that bypass the controls (the API, imports). In the extension strand the same need is met by a Function that reads thresholds; here the trade-off is visible in the design, which is what a reviewer looks for.
Downstream touch-points
Section titled “Downstream touch-points”Every engine part that switches on the data type may need to know the new one. For each, decide supported, declared unsupported (the control’s metadata says so, M8-S3), or follow-up:
| Touch-point | The question | Meter reading on this strand |
|---|---|---|
| Field builder helper (shared package) | Can code and seeds create a field of the type? | Supported: it takes any data-type value |
| Queries and filters | Can a list be filtered on the field? | Declared unsupported at first; filtering on value inside the object is a follow-up |
| Statistics and counters | Can it be summed or averaged? | Declared unsupported: an object is not a number |
| Search indexing | Is it searchable or usable as a title? | Declared unsupported |
| Exports and templates | How is it printed? | Follow-up: shown as “value unit” |
| Mobile | Does the phone render it? | M8-S4: a component or a declared fallback |
What to notice: “declared unsupported” is a legitimate answer. What is not acceptable is a touch-point nobody considered, because the platform’s default for an unknown type is usually to pass it through quietly.
Tenant-safe by construction
Section titled “Tenant-safe by construction”The caster runs inside the tenant and space the platform has already established for the request, so the safest caster is a pure function: no cache, no module-level state, no messages, no lookups. If a future version needed data (for example a tenant’s own unit catalogue), it would read it through the tenant-scoped repositories and follow the engine’s tenant-aware recipes: carry the space on every message, never build a cache key by hand, never fall back to the root space. Write that rule into the caster’s file header, so the next engineer sees it.
▶ Guided demo (7 min) — Read the newest field type first
Section titled “▶ Guided demo (7 min) — Read the newest field type first”Starting state. Your three checkouts on feat/meter-reading, nothing changed yet. The best guide to
what a field type touches is the last one added. Follow it through the code bases.
-
Find it in the shared contract. In the services workspace:
Terminal window grep -rn "SVGIcon" packages/osos-shared/src/models/enums.tsExpected: one line in the data-type enum, with an explicit number.
-
Find what the services do with it.
Terminal window grep -rln "SVGIcon" services/data-service/src | grep -v __tests__Expected: its caster, the expression engine’s result rule, and the migration that seeded the type’s core entity. Open the caster: it passes a text through only when it contains no unsafe content, and returns
nullotherwise, which is the pattern you will follow. -
Find it in the web front end and the mobile app. From the web workspace and the mobile workspace respectively:
Terminal window grep -rln "SVGIcon" libs/shared/types/srcgrep -rln "SVGIcon" packages/osos_domain/libExpected: the web enum lists
SVGIcon = 14. The mobile domain package’sDataTypeEnumstops atobjectJson(13)and has noSVGIconmember, so the second command prints nothing; the lab later adds it there. -
Note what it did not need. No change to queries, statistics or search: the icon is not filtered or summed. Your type will be the same, except that you must declare it, because a reading looks like something people would want to filter.
✓ Practice (4 min) — The contract and the caster
Section titled “✓ Practice (4 min) — The contract and the caster”A teammate proposes giving MeterReading the number 11, “because it is free in our branch”. On the
released line, 11 already belongs to another data type. What happens if the change ships?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
The sensor feed posts {"value": "6,5", "unit": "bar"} (a comma as decimal separator). What should the
Meter reading caster store, and why?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
Why can’t the Meter reading caster enforce “vibration between 0 and 50 mm/s” for the field Last vibration reading?
Check your answer
The correct answer is C. Open the explanation under each option to see why.
⛏ Lab (47 min) — Add Meter reading to the engine, test-first
Section titled “⛏ Lab (47 min) — Add Meter reading to the engine, test-first”Goal. The MeterReading data type in the shared contract of all three code bases with the same
number, a caster that normalises it with passing tests, an expression rule with a passing test, and a
written list of downstream decisions.
Before you start. Your source workbench from M8-S1; feat/meter-reading checked out in the three
code bases; the services running are not needed for this lab (tests only).
The value contract
-
In the services workspace, add
MeterReadingto the data-type enum in the shared package, afterSVGIcon, with the explicit number you chose (15on the 1.10 line). -
In the web workspace, add the same member with the same number to the mirrored data-type enum you found in the demo.
-
In the mobile workspace, add the same member with the same number to the domain package’s mirror, declared the same way as its neighbours.
-
Run the contract check across the three, from the folder that holds them:
Terminal window grep -rhoE "MeterReading[^,;]*" \backend/packages/osos-shared/src/models/enums.ts \frontend/libs/shared/types/src \mobile-app/packages/osos_domain/libExpected: three lines that all carry the same number.
-
In the mobile workspace, run the analyser, then list the switches over the data type and keep the list:
Terminal window melos run analyzegrep -rn "case DataTypeEnum\." lib packages > ~/meter-reading-mobile-todo.txtExpected: no new errors. The list holds one switch, the template-parameter value factory, and it has a
defaultbranch that returns no value; a data-type number the mirror does not know is read as text. So the data type gives the compiler nothing to report: what the phone draws is chosen by the field’s component ids, and M8-S4 starts from those. Keep the file; the mobile app still builds.
The caster, test-first
-
In the data service’s unit tests, create the caster’s test file and write the four cases first:
import {expect} from '@loopback/testlab';import {MeterReadingCaster} from '../../../casters/meter-reading.caster';describe('MeterReadingCaster', () => {const caster = new MeterReadingCaster();it('keeps a well-formed reading', () => {expect(caster.cast({value: 4.2, unit: ' mm/s '})).to.eql({value: 4.2, unit: 'mm/s'});});it('reads a value written as text', () => {expect(caster.cast('6.5 bar')).to.eql({value: 6.5, unit: 'bar'});});it('accepts a bare number without a unit', () => {expect(caster.cast(71)).to.eql({value: 71, unit: null});});it('refuses anything it cannot read as a finite number', () => {for (const bad of ['high', '6,5 bar', NaN, Infinity, {value: 'x'}, {unit: 'bar'}, [], true]) {expect(caster.cast(bad)).to.be.null();}});}); -
Run the data service’s tests. Expected: the new test file fails to compile, because the caster does not exist yet. That is the right start.
-
Create
meter-reading.caster.tsin the data service’scastersfolder:import {injectable} from '@loopback/core';import {DataTypeEnum} from '@osos/shared';import {ICaster} from './types';// Pure by design: no I/O, no cache, no module state. It runs inside the tenant and space// the platform established for the request; keep it that way (tenant-aware recipes).export interface MeterReadingValue {value: number;unit: string | null;}@injectable()export class MeterReadingCaster implements ICaster {static castType = DataTypeEnum.MeterReading;cast(input: unknown): MeterReadingValue | null {if (typeof input === 'number') {return Number.isFinite(input) ? {value: input, unit: null} : null;}if (typeof input === 'string') {const m = input.trim().match(/^(-?\d+(?:\.\d+)?)(?:\s+(\S.*))?$/);return m ? {value: Number(m[1]), unit: m[2]?.trim() || null} : null;}if (input && typeof input === 'object' && !Array.isArray(input)) {const {value, unit} = input as {value?: unknown; unit?: unknown};const n = typeof value === 'string' && value.trim() !== '' ? Number(value) : value;if (typeof n !== 'number' || !Number.isFinite(n)) return null;return {value: n, unit: typeof unit === 'string' && unit.trim() ? unit.trim() : null};}return null;}} -
Rebuild the shared package and the data service, then run the tests. Expected: the four caster tests pass, with every other test.
-
Check the caster is discovered: in the test folder, add one test that resolves the caster for
DataTypeEnum.MeterReadingthrough the same factory the save path uses, and run it. No existing test sets the factory up, so build it yourself: a LoopBackContextwith the caster bound atcaster.<data type number>(the prefix the casters booter uses), thennew CasterFactoryService(ctx).getCaster(...). Expected: it returns aMeterReadingCaster.
The expression rule
-
Find the expression engine’s result check:
Terminal window grep -rn "validateExpressionResult" services/data-service/src | grep -v __tests__ | head -3 -
Add a case for
DataTypeEnum.MeterReading: the result is valid only if it is an object with a finite numericvalue. Follow the neighbouring cases, including the exception they raise. -
Add a test beside the existing tests of that check: a result of
{value: 3, unit: 'bar'}passes, a result of3is refused. Rebuild and run. Expected: green.
The downstream decisions
- Copy the touch-point table from the concept into your notes and fill the last column for your
build, adding any touch-point you found with
grep -rn "DataTypeEnum\." services/*/src | grep -v __tests__that the table does not list. - Commit on
feat/meter-readingin each code base, with a message that names the data-type number and the stored shape.
Check.
- The contract check prints the same number three times.
- The mobile analyser reports no new errors, and your to-do file names the one switch over the data type and its
default. - The caster’s four tests failed before the caster existed and pass now.
- The factory resolves a
MeterReadingCasterfor the new type. - The expression rule accepts a reading and refuses a bare number, with a test for each.
- Your touch-point table has a decision on every row, including any you found yourself.
- Each code base has one commit on
feat/meter-reading.
Pass condition. All tests in the data service pass, including the new caster, factory and expression tests; the three enums agree on the number; and every touch-point has a written decision.
If something goes wrong
| What you see | What to do |
|---|---|
Property 'MeterReading' does not exist on type 'typeof DataTypeEnum' | The data service is compiled against the old shared package. Rebuild the shared package first, then the service. |
The factory test returns undefined | The caster was not discovered: check the file suffix .caster.ts, the static castType, and that you rebuilt. |
The '6.5 bar' test fails with unit: null | The pattern needs a space between value and unit; send "6.5 bar", or widen the pattern deliberately and add a test for it. |
{unit: 'bar'} is not refused | An object without a value gives undefined; make sure the check is typeof n !== 'number', not a truthiness test. |
| The contract check prints different numbers | Fix the code base that differs before anything else; a mismatch here breaks rendering silently. |
Model answer
The contract check:
MeterReading = 15MeterReading = 15MeterReading(15)(The mobile mirror may be written in its own enum syntax; what matters is the number.)
The expression rule (in the same style as its neighbours):
case DataTypeEnum.MeterReading: if (!result || typeof result !== 'object' || !Number.isFinite((result as {value?: unknown}).value as number)) { this.throwInvalidTypeException(result, expectedDataType); } break;The touch-point decisions:
| Touch-point | Decision |
|---|---|
| Field builder helper | Supported, no change needed |
| Queries and filters | Declared unsupported in the control’s metadata; follow-up: filter on value |
| Statistics and counters | Declared unsupported |
| Search and title | Declared unsupported |
| Exports and templates | Follow-up: print as “4.2 mm/s”; until then the object is shown |
| Mobile | M8-S4, from the component switches; the data type alone gives the analyser nothing to list |
| Range per field | Enforced by the web and mobile controls; the server guarantees well-formed readings only (recorded decision) |
The commit message: feat: add MeterReading data type (15), stored as {value: number, unit: string|null}, caster refuses unreadable input.
✓ Practice (5 min) — Downstream and tenant-safe
Section titled “✓ Practice (5 min) — Downstream and tenant-safe”A colleague’s version of the caster looks up each unit in a cache of “approved units”, building the cache key from the unit text. What is the problem?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
A builder makes a calculated Meter reading field whose formula returns the number 4.2, before you
added the expression rule. What did the engine store?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
A review asks why Meter reading is a new data type rather than a custom control over the JSON type, which would have avoided changing the services. Which answer holds?
Check your answer
The correct answer is C. Open the explanation under each option to see why.
Six months after release, planners ask to store the reading’s timestamp inside the value:
{value, unit, takenAt}. What does that change mean?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
↺ Recap (1 min) — What you can now do
Section titled “↺ Recap (1 min) — What you can now do”You can add a field type to the engine as a contract: a data-type number that is the same in all three code bases and never reused, a stored shape decided before the first record, a caster that normalises every write and refuses what it cannot read, an expression rule so calculated values are checked, a written decision for every downstream touch-point, and code that stays tenant-safe because it is pure. You also chose a new data type over a control-only design for a stated reason.
Next. In M8-S3 you give the type a web control: the designer offers it to builders with a unit and a range they set themselves, and the portal shows and edits readings, with the range enforced where the field is known.