TypeScript / Tested teaching helper
Allowlist a synthetic sensor message
Validate a small telemetry payload and drop unknown fields.
TypeScript
export function validatedSensorMessage(input:unknown):{deviceId:string;temperatureC:number}|null{
if(!input||typeof input!=="object"||Array.isArray(input))return null;
const record=input as Record<string,unknown>;
if(typeof record.deviceId!=="string"||!/^[-a-z0-9]{1,24}$/.test(record.deviceId))return null;
const value=record.temperatureC;
if(typeof value!=="number"||!Number.isFinite(value)||value< -40||value>125)return null;
return {deviceId:record.deviceId,temperatureC:value};
}What matters
Syntactic validation is not device authentication, message integrity, freshness or authorization. A production ingestion service also needs authenticated identity, replay controls, quotas, timestamps and storage policies.
Test these cases
- Valid temperature returns a stable shape
- Unexpected token field never appears in output
- Malformed IDs and out-of-range readings are rejected
Sources and limits
This is a reference snippet, not a substitute for reviewing the full vendor API contract, concurrency rules or production threat model. Do not paste secrets into sample code.
This pure helper has runnable Node.js tests in the downloadable educational bundle. Those tests do not verify a full production security system.
