Skip to content

hap-fluent / wrapService

Function: wrapService()

ts
function wrapService<T>(service): FluentService<T>;

Defined in: packages/hap-fluent/src/FluentService.ts:300

Wrap an existing HAP Service instance with the fluent helper interface.

Type Parameters

Type Parameter
T extends typeof Service

Parameters

ParameterTypeDescription
serviceInstanceType<T>A valid hap-nodejs Service instance to wrap.

Returns

FluentService<T>

A FluentService providing typed .characteristics, .onGet(), .onSet(), .update(), and shorthand property accessors.

Remarks

wrapService builds a FluentService around a service that was obtained externally (e.g., from platformAccessory.getService() or created manually). It iterates service.characteristics at call time and creates one FluentCharacteristic per characteristic, keyed by camelCase display name.

Characteristics added to the service after this call will not appear in .characteristics — call wrapService again to refresh the map, or add optional characteristics to the service before wrapping.

Throws

If service does not satisfy the isService() type guard (i.e., is missing UUID, displayName, getCharacteristic, or addCharacteristic).

Use When

  • You already hold a raw Service instance (e.g., obtained via platformAccessory.services during configureAccessory()) and want the fluent API without the lookup overhead of getOrAddService.
  • You are writing unit tests that construct Service instances directly.

Avoid When

  • You don't yet have a service instance — use getOrAddService which handles both creation and wrapping in a single call.

Pitfalls

  • NEVER wrap the same service instance more than once and register different handlers on each wrapper — both wrappers share the underlying hap-nodejs characteristic objects, so handlers registered on one wrapper overwrite those on the other.
  • NEVER add characteristics to the service after calling wrapService and expect them to appear in .characteristics — the snapshot is taken at wrap time.

Example

typescript
import { wrapService } from 'hap-fluent';

// During configureAccessory() when restoring cached accessories
const rawService = accessory.getService(hap.Service.Lightbulb);
if (rawService) {
  const lightbulb = wrapService(rawService);
  lightbulb.onGet('on', async () => fetchState());
}

Released under the Apache-2.0 License.