Skip to content
ModuleM8 — Extend the engine from source (source strand)
After this session you canAdd 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.
Time74 min with a facilitator · about 74 min on your own
Before you startM8-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 deeperHow 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”

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 typeNew data type
Code bases changedWeb and mobileServices, web and mobile
Normalisation on saveNone: the JSON caster passes any object through unchangedYour caster normalises every save, whatever the client
Calculated fieldsResults of the object types are returned uncheckedYou 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 costLowerHigher: 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 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 (71 becomes {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 into NaN;
  • trim units, and store a missing unit as null rather than an empty text.

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.

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-pointThe questionMeter 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 filtersCan a list be filtered on the field?Declared unsupported at first; filtering on value inside the object is a follow-up
Statistics and countersCan it be summed or averaged?Declared unsupported: an object is not a number
Search indexingIs it searchable or usable as a title?Declared unsupported
Exports and templatesHow is it printed?Follow-up: shown as “value unit”
MobileDoes 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.

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.

  1. Find it in the shared contract. In the services workspace:

    Terminal window
    grep -rn "SVGIcon" packages/osos-shared/src/models/enums.ts

    Expected: one line in the data-type enum, with an explicit number.

  2. 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 null otherwise, which is the pattern you will follow.

  3. 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/src
    grep -rln "SVGIcon" packages/osos_domain/lib

    Expected: the web enum lists SVGIcon = 14. The mobile domain package’s DataTypeEnum stops at objectJson(13) and has no SVGIcon member, so the second command prints nothing; the lab later adds it there.

  4. 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”
PracticeChoose one answer.

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?

  1. Explanation for A

    ✓ Correct

    Correct: field definitions store the number, so reusing it re-labels every existing field of the other type. See the value contract.

  2. Explanation for B

    ✗ Incorrect

    Not this one: the number is stored in every field definition and mirrored in both front ends. See the value contract.

  3. Explanation for C

    ✗ Incorrect

    Not this one: the clash is with the released line’s stored data, which no build can see. See M2-S3: the wire contract.

Check your answer

The correct answer is A. Open the explanation under each option to see why.

PracticeChoose one answer.

The sensor feed posts {"value": "6,5", "unit": "bar"} (a comma as decimal separator). What should the Meter reading caster store, and why?

  1. Explanation for A

    ✗ Incorrect

    Not this one: NaN is the silent failure the session warned against; it looks like a value and poisons every later calculation. See the caster.

  2. Explanation for B

    ✓ Correct

    Correct: a caster refuses what it cannot read; the sender fixes its format, and the empty reading is visible as missing, not as wrong. See the caster.

  3. Explanation for C

    ✗ Incorrect

    Not this one: guessing produces a plausible wrong value, which is worse than none. See the caster.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

Why can’t the Meter reading caster enforce “vibration between 0 and 50 mm/s” for the field Last vibration reading?

  1. Explanation for A

    ✗ Incorrect

    Not this one: returning null for unreadable input is exactly what the caster does. See the range check.

  2. Explanation for B

    ✗ Incorrect

    Not this one: a Function is one option in the extension strand; the question is what the caster can see. See the range check.

  3. Explanation for C

    ✓ Correct

    Correct: the range is per field, configured by the builder, and only the controls receive the field. See the range check.

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

  1. In the services workspace, add MeterReading to the data-type enum in the shared package, after SVGIcon, with the explicit number you chose (15 on the 1.10 line).

  2. In the web workspace, add the same member with the same number to the mirrored data-type enum you found in the demo.

  3. 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.

  4. 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/lib

    Expected: three lines that all carry the same number.

  5. In the mobile workspace, run the analyser, then list the switches over the data type and keep the list:

    Terminal window
    melos run analyze
    grep -rn "case DataTypeEnum\." lib packages > ~/meter-reading-mobile-todo.txt

    Expected: no new errors. The list holds one switch, the template-parameter value factory, and it has a default branch 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

  1. 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();
    }
    });
    });
  2. 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.

  3. Create meter-reading.caster.ts in the data service’s casters folder:

    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;
    }
    }
  4. Rebuild the shared package and the data service, then run the tests. Expected: the four caster tests pass, with every other test.

  5. Check the caster is discovered: in the test folder, add one test that resolves the caster for DataTypeEnum.MeterReading through the same factory the save path uses, and run it. No existing test sets the factory up, so build it yourself: a LoopBack Context with the caster bound at caster.<data type number> (the prefix the casters booter uses), then new CasterFactoryService(ctx).getCaster(...). Expected: it returns a MeterReadingCaster.

The expression rule

  1. Find the expression engine’s result check:

    Terminal window
    grep -rn "validateExpressionResult" services/data-service/src | grep -v __tests__ | head -3
  2. Add a case for DataTypeEnum.MeterReading: the result is valid only if it is an object with a finite numeric value. Follow the neighbouring cases, including the exception they raise.

  3. Add a test beside the existing tests of that check: a result of {value: 3, unit: 'bar'} passes, a result of 3 is refused. Rebuild and run. Expected: green.

The downstream decisions

  1. 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.
  2. Commit on feat/meter-reading in 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 MeterReadingCaster for 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 seeWhat 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 undefinedThe 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: nullThe 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 refusedAn object without a value gives undefined; make sure the check is typeof n !== 'number', not a truthiness test.
The contract check prints different numbersFix the code base that differs before anything else; a mismatch here breaks rendering silently.
Model answer

The contract check:

MeterReading = 15
MeterReading = 15
MeterReading(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-pointDecision
Field builder helperSupported, no change needed
Queries and filtersDeclared unsupported in the control’s metadata; follow-up: filter on value
Statistics and countersDeclared unsupported
Search and titleDeclared unsupported
Exports and templatesFollow-up: print as “4.2 mm/s”; until then the object is shown
MobileM8-S4, from the component switches; the data type alone gives the analyser nothing to list
Range per fieldEnforced 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”
PracticeChoose one answer.

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?

  1. Explanation for A

    ✓ Correct

    Correct: the tenant-aware rules forbid hand-built keys; a pure caster needs no cache at all. See tenant-safe by construction.

  2. Explanation for B

    ✗ Incorrect

    Not this one: a short expiry shortens the leak but does not scope the key to the tenant. See tenant-safe by construction.

  3. Explanation for C

    ✗ Incorrect

    Not this one: the booter registers any class with the right file and static field; the risk is in what the class does. See tenant-safe by construction.

Check your answer

The correct answer is A. Open the explanation under each option to see why.

PracticeChoose one answer.

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?

  1. Explanation for A

    ✗ Incorrect

    Not this one: without a rule for the type, the check has nothing to compare against and lets the result through. See the expression rule.

  2. Explanation for B

    ✓ Correct

    Correct: results of types without a rule are not checked, so the wrong shape was stored; your rule closes that gap. See the expression rule.

  3. Explanation for C

    ✗ Incorrect

    Not this one: casters coerce submitted values; calculated results go through the expression engine’s own check. See the expression rule.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

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?

  1. Explanation for A

    ✗ Incorrect

    Not this one: controls over existing types are offered normally; the category field works that way. See what a field type is.

  2. Explanation for B

    ✗ Incorrect

    Not this one: the choice was not about speed, and filtering is declared unsupported at first. See downstream touch-points.

  3. Explanation for C

    ✓ Correct

    Correct: a check that lives in a control is skipped by every writer that has no control; the caster sees every save. See what a field type is.

Check your answer

The correct answer is C. Open the explanation under each option to see why.

PracticeChoose one answer.

Six months after release, planners ask to store the reading’s timestamp inside the value: {value, unit, takenAt}. What does that change mean?

  1. Explanation for A

    ✗ Incorrect

    Not this one: stored records already hold the old shape, and every reader assumes it. See the value contract.

  2. Explanation for B

    ✓ Correct

    Correct: the shape is a wire contract like the number; changing it touches stored data and every reader. See M2-S4: migrations.

  3. Explanation for C

    ✗ Incorrect

    Not this one: old records would lack the timestamp and new readers would rely on it; that gap needs a migration. See the value contract.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

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.