Skip to content

Commit

Permalink
refactor: rename getNodeUnsafe to tryGetNode
Browse files Browse the repository at this point in the history
  • Loading branch information
AlCalzone committed Oct 16, 2024
1 parent d902697 commit 838723c
Show file tree
Hide file tree
Showing 12 changed files with 53 additions and 49 deletions.
4 changes: 2 additions & 2 deletions docs/api/endpoint.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ createCCInstanceUnsafe<T>(cc: CommandClasses): T | undefined

Like [`createCCInstance`](#createCCInstance) but returns `undefined` instead of throwing when a CC is not supported.

### `getNodeUnsafe`
### `tryGetNode`

```ts
getNodeUnsafe(): ZWaveNode | undefined
tryGetNode(): ZWaveNode | undefined
```

Returns the node this endpoint belongs to (or undefined if the node doesn't exist).
Expand Down
2 changes: 1 addition & 1 deletion packages/cc/src/lib/API.ts
Original file line number Diff line number Diff line change
Expand Up @@ -888,7 +888,7 @@ export type APIMethodsOf<CC extends CCNameOrId> = Omit<
OnlyMethods<CCToAPI<CC>>,
| "ccId"
| "getNode"
| "getNodeUnsafe"
| "tryGetNode"
| "isSetValueOptimistic"
| "isSupported"
| "pollValue"
Expand Down
2 changes: 1 addition & 1 deletion packages/cc/src/lib/CommandClass.ts
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,7 @@ export class CommandClass implements CCId {
* @internal
* Returns the node this CC is linked to (or undefined if the node doesn't exist)
*/
public getNodeUnsafe<T extends NodeId>(
public tryGetNode<T extends NodeId>(
ctx: GetNode<T>,
): T | undefined {
try {
Expand Down
36 changes: 20 additions & 16 deletions packages/serial/src/message/Message.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ test("should deserialize and serialize correctly", (t) => {
]),
];
for (const original of okayMessages) {
const parsed = new Message({ data: original });
t.deepEqual(parsed.serialize(), original);
const parsed = new Message({ data: original, ctx: {} as any });
t.deepEqual(parsed.serialize({} as any), original);
}
});

Expand All @@ -53,7 +53,7 @@ test("should serialize correctly when the payload is null", (t) => {
type: MessageType.Request,
functionType: 0xff as any,
});
t.deepEqual(message.serialize(), expected);
t.deepEqual(message.serialize({} as any), expected);
});

test("should throw the correct error when parsing a faulty message", (t) => {
Expand Down Expand Up @@ -92,10 +92,14 @@ test("should throw the correct error when parsing a faulty message", (t) => {
],
];
for (const [message, msg, code] of brokenMessages) {
assertZWaveError(t, () => new Message({ data: message }), {
messageMatches: msg,
errorCode: code,
});
assertZWaveError(
t,
() => new Message({ data: message, ctx: {} as any }),
{
messageMatches: msg,
errorCode: code,
},
);
}
});

Expand Down Expand Up @@ -321,7 +325,7 @@ test(`the constructor should throw when no message type is specified`, (t) => {
@messageTypes(undefined as any, 0xff as any)
class FakeMessageWithoutMessageType extends Message {}

assertZWaveError(t, () => new FakeMessageWithoutMessageType(host), {
assertZWaveError(t, () => new FakeMessageWithoutMessageType(), {
errorCode: ZWaveErrorCodes.Argument_Invalid,
messageMatches: /message type/i,
});
Expand All @@ -341,31 +345,31 @@ test(`the constructor should throw when no function type is specified`, (t) => {
@messageTypes(MessageType.Request, undefined as any)
class FakeMessageWithoutFunctionType extends Message {}

assertZWaveError(t, () => new FakeMessageWithoutFunctionType(host), {
assertZWaveError(t, () => new FakeMessageWithoutFunctionType(), {
errorCode: ZWaveErrorCodes.Argument_Invalid,
messageMatches: /function type/i,
});
});

test("getNodeUnsafe() returns undefined when the controller is not initialized yet", (t) => {
test("tryGetNode() returns undefined when the controller is not initialized yet", (t) => {
const host = createTestingHost();
const msg = new Message({
type: MessageType.Request,
functionType: 0xff as any,
});
t.is(msg.getNodeUnsafe(host), undefined);
t.is(msg.tryGetNode(host), undefined);
});

test("getNodeUnsafe() returns undefined when the message is no node query", (t) => {
test("tryGetNode() returns undefined when the message is no node query", (t) => {
const host = createTestingHost();
const msg = new Message({
type: MessageType.Request,
functionType: 0xff as any,
});
t.is(msg.getNodeUnsafe(host), undefined);
t.is(msg.tryGetNode(host), undefined);
});

test("getNodeUnsafe() returns the associated node otherwise", (t) => {
test("tryGetNode() returns the associated node otherwise", (t) => {
const host = createTestingHost();
host.setNode(1, {} as any);

Expand All @@ -376,9 +380,9 @@ test("getNodeUnsafe() returns the associated node otherwise", (t) => {

// This node exists
(msg as any as INodeQuery).nodeId = 1;
t.is(msg.getNodeUnsafe(host), host.getNode(1));
t.is(msg.tryGetNode(host), host.getNode(1));

// This one does
(msg as any as INodeQuery).nodeId = 2;
t.is(msg.getNodeUnsafe(host), undefined);
t.is(msg.tryGetNode(host), undefined);
});
8 changes: 4 additions & 4 deletions packages/serial/src/message/Message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ import {
} from "@zwave-js/core";
import type {
GetDeviceConfig,
GetNode,
GetSupportedCCVersion,
HostIDs,
ZWaveApplicationHost,
} from "@zwave-js/host";
import type { JSONObject, TypedClassDecorator } from "@zwave-js/shared/safe";
import { num2hex, staticExtends } from "@zwave-js/shared/safe";
Expand Down Expand Up @@ -453,11 +453,11 @@ export class Message {
/**
* Returns the node this message is linked to or undefined
*/
public getNodeUnsafe<T extends NodeId>(
applHost: ZWaveApplicationHost<T>,
public tryGetNode<T extends NodeId>(
ctx: GetNode<T>,
): T | undefined {
const nodeId = this.getNodeId();
if (nodeId != undefined) return applHost.getNode(nodeId);
if (nodeId != undefined) return ctx.getNode(nodeId);
}

private _transmissionTimestamp: number | undefined;
Expand Down
28 changes: 14 additions & 14 deletions packages/zwave-js/src/lib/driver/Driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1007,7 +1007,7 @@ export class Driver extends TypedEventEmitter<DriverEventCallbacks>
return [...this.controller.nodes.values()];
}

public getNodeUnsafe(msg: Message): ZWaveNode | undefined {
public tryGetNode(msg: Message): ZWaveNode | undefined {
const nodeId = msg.getNodeId();
if (nodeId != undefined) return this.controller.nodes.get(nodeId);
}
Expand Down Expand Up @@ -3501,7 +3501,7 @@ export class Driver extends TypedEventEmitter<DriverEventCallbacks>
}, this._requestContext);
if (isCommandClassContainer(msg)) {
// Whether successful or not, a message from a node should update last seen
const node = this.getNodeUnsafe(msg);
const node = this.tryGetNode(msg);
if (node) node.lastSeen = new Date();

// Ensure there are no errors
Expand All @@ -3510,7 +3510,7 @@ export class Driver extends TypedEventEmitter<DriverEventCallbacks>
// And update statistics
if (!!this._controller) {
if (isCommandClassContainer(msg)) {
this.getNodeUnsafe(msg)?.incrementStatistics("commandsRX");
this.tryGetNode(msg)?.incrementStatistics("commandsRX");
} else {
this._controller.incrementStatistics("messagesRX");
}
Expand All @@ -3526,7 +3526,7 @@ export class Driver extends TypedEventEmitter<DriverEventCallbacks>
if (response) await this.writeHeader(response);
if (!!this._controller) {
if (isCommandClassContainer(msg)) {
this.getNodeUnsafe(msg)?.incrementStatistics(
this.tryGetNode(msg)?.incrementStatistics(
"commandsDroppedRX",
);

Expand All @@ -3538,7 +3538,7 @@ export class Driver extends TypedEventEmitter<DriverEventCallbacks>
&& msg.command instanceof InvalidCC
) {
// If it was, we need to notify the sender that we couldn't decode the command
const node = this.getNodeUnsafe(msg);
const node = this.tryGetNode(msg);
if (node) {
const endpoint = node.getEndpoint(
msg.command.endpointIndex,
Expand Down Expand Up @@ -3606,7 +3606,7 @@ export class Driver extends TypedEventEmitter<DriverEventCallbacks>
msg.command
instanceof SecurityCCCommandEncapsulationNonceGet
) {
void this.getNodeUnsafe(msg)?.handleSecurityNonceGet();
void this.tryGetNode(msg)?.handleSecurityNonceGet();
}

// Transport Service commands must be handled before assembling partial CCs
Expand Down Expand Up @@ -3822,7 +3822,7 @@ export class Driver extends TypedEventEmitter<DriverEventCallbacks>
if (!encapS2) return false;

// With the MGRP extension present
const node = this.getNodeUnsafe(msg);
const node = this.tryGetNode(msg);
if (!node) return false;
const groupId = encapS2.getMulticastGroupId();
if (groupId == undefined) return false;
Expand Down Expand Up @@ -4007,7 +4007,7 @@ export class Driver extends TypedEventEmitter<DriverEventCallbacks>
},
error: ZWaveError,
): boolean {
const node = this.getNodeUnsafe(transaction.message);
const node = this.tryGetNode(transaction.message);
if (!node) return false; // This should never happen, but whatever

const messagePart1 = isSendData(transaction.message)
Expand Down Expand Up @@ -4172,7 +4172,7 @@ export class Driver extends TypedEventEmitter<DriverEventCallbacks>
|| this._recoveryPhase
=== ControllerRecoveryPhase.CallbackTimeoutAfterReset
) {
const node = this.getNodeUnsafe(transaction.message);
const node = this.tryGetNode(transaction.message);
if (!node) return false; // This should never happen, but whatever

// The controller is still timing out transmitting after a soft reset, don't try again.
Expand Down Expand Up @@ -4980,7 +4980,7 @@ ${handlers.length} left`,
let handlers: RequestHandlerEntry[] | undefined;

if (isNodeQuery(msg) || isCommandClassContainer(msg)) {
const node = this.getNodeUnsafe(msg);
const node = this.tryGetNode(msg);
if (node) {
// We have received an unsolicited message from a dead node, bring it back to life
if (node.status === NodeStatus.Dead) {
Expand Down Expand Up @@ -5427,7 +5427,7 @@ ${handlers.length} left`,
result: Message | undefined,
): void {
// Update statistics
const node = this.getNodeUnsafe(msg);
const node = this.tryGetNode(msg);
let success = true;
if (isSendData(msg) || isNodeQuery(msg)) {
// This shouldn't happen, but just in case
Expand Down Expand Up @@ -5528,7 +5528,7 @@ ${handlers.length} left`,
}

const message = transaction.message;
const targetNode = message.getNodeUnsafe(this);
const targetNode = message.tryGetNode(this);

// Messages to the controller may always be sent...
if (!targetNode) return true;
Expand Down Expand Up @@ -5949,7 +5949,7 @@ ${handlers.length} left`,

let node: ZWaveNode | undefined;
if (isNodeQuery(msg) || isCommandClassContainer(msg)) {
node = this.getNodeUnsafe(msg);
node = this.tryGetNode(msg);
}

if (options.priority == undefined) {
Expand Down Expand Up @@ -7073,7 +7073,7 @@ ${handlers.length} left`,

/** Determines time in milliseconds to wait for a report from a node */
public getReportTimeout(msg: Message): number {
const node = this.getNodeUnsafe(msg);
const node = this.tryGetNode(msg);

return (
// If there's a message-specific timeout, use that
Expand Down
2 changes: 1 addition & 1 deletion packages/zwave-js/src/lib/driver/MessageGenerators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ export const maybeTransportServiceGenerator: MessageGeneratorImplementation =
);
}

const node = msg.getNodeUnsafe(driver);
const node = msg.tryGetNode(driver);
const mayUseTransportService =
node?.supportsCC(CommandClasses["Transport Service"])
&& node.getCCVersion(CommandClasses["Transport Service"]) >= 2;
Expand Down
8 changes: 4 additions & 4 deletions packages/zwave-js/src/lib/driver/Transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,8 @@ export class Transaction implements Comparable<Transaction> {
_this: Transaction,
_other: Transaction,
): CompareResult | undefined => {
const thisNode = _this.message.getNodeUnsafe(this.driver);
const otherNode = _other.message.getNodeUnsafe(this.driver);
const thisNode = _this.message.tryGetNode(this.driver);
const otherNode = _other.message.tryGetNode(this.driver);

// We don't require existence of the node object
// If any transaction is not for a node, it targets the controller
Expand All @@ -222,8 +222,8 @@ export class Transaction implements Comparable<Transaction> {
_this: Transaction,
_other: Transaction,
): CompareResult | undefined => {
const thisNode = _this.message.getNodeUnsafe(this.driver);
const otherNode = _other.message.getNodeUnsafe(this.driver);
const thisNode = _this.message.tryGetNode(this.driver);
const otherNode = _other.message.tryGetNode(this.driver);
if (thisNode && otherNode) {
// Both nodes exist
const thisListening = thisNode.isListening
Expand Down
2 changes: 1 addition & 1 deletion packages/zwave-js/src/lib/log/Driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ export class DriverLogger extends ZWaveLoggerBase<DriverLogContext> {
if (queue.length > 0) {
for (const trns of queue.transactions) {
// TODO: This formatting should be shared with the other logging methods
const node = trns.message.getNodeUnsafe(this.driver);
const node = trns.message.tryGetNode(this.driver);
const prefix = trns.message.type === MessageType.Request
? "[REQ]"
: "[RES]";
Expand Down
6 changes: 3 additions & 3 deletions packages/zwave-js/src/lib/node/MultiCCAPIWrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export function createMultiCCAPIWrapper<T extends CCAPI>(apiInstances: T[]): T {

// This wrapper is by definition for multiple nodes, so we cannot return one
const getNode = () => undefined;
const getNodeUnsafe = () => undefined;
const tryGetNode = () => undefined;

return new Proxy({} as T, {
get(target, prop) {
Expand All @@ -81,8 +81,8 @@ export function createMultiCCAPIWrapper<T extends CCAPI>(apiInstances: T[]): T {
return isSupported;
case "getNode":
return getNode;
case "getNodeUnsafe":
return getNodeUnsafe;
case "tryGetNode":
return tryGetNode;
case "isSetValueOptimistic":
return isSetValueOptimistic;
case "supportsCommand":
Expand Down
2 changes: 1 addition & 1 deletion packages/zwave-js/src/lib/test/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { MessageType } from "@zwave-js/serial";

const defaultImplementations = {
serialize: () => Buffer.from([1, 2, 3]),
getNodeUnsafe: () => undefined,
tryGetNode: () => undefined,
getNodeId: () => undefined,
toLogEntry: () => ({ tags: [] }),
needsCallbackId: () => true,
Expand Down
2 changes: 1 addition & 1 deletion packages/zwave-js/src/lib/test/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ export function createTestEndpoint(
> {
throw new Error("Function not implemented.");
},
getNodeUnsafe: function(): IZWaveNode | undefined {
tryGetNode: function(): IZWaveNode | undefined {

Check failure on line 392 in packages/zwave-js/src/lib/test/mocks.ts

View workflow job for this annotation

GitHub Actions / lint (18)

'IZWaveNode' is an 'error' type that acts as 'any' and overrides all other types in this union type

Check failure on line 392 in packages/zwave-js/src/lib/test/mocks.ts

View workflow job for this annotation

GitHub Actions / lint (18)

'IZWaveNode' is an 'error' type that acts as 'any' and overrides all other types in this union type
return host.nodes.get(options.nodeId);
},
};
Expand Down

0 comments on commit 838723c

Please sign in to comment.