Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: enable strict-boolean-expressions globally #1127

Merged
merged 5 commits into from
Oct 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ module.exports = {
"@typescript-eslint/no-use-before-define": ["error"],
"@typescript-eslint/prefer-nullish-coalescing": "error",
"unused-imports/no-unused-imports": "error",
"@typescript-eslint/strict-boolean-expressions": "error",
"unused-imports/no-unused-vars": [
"warn",
{
Expand Down
5 changes: 1 addition & 4 deletions packages/binding-coap/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
{
"extends": "../../.eslintrc.js",
"rules": {
"@typescript-eslint/strict-boolean-expressions": ["error"]
}
"extends": "../../.eslintrc.js"
}
2 changes: 1 addition & 1 deletion packages/binding-file/src/file-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export default class FileClient implements ProtocolClient {
const extension = path.extname(filepath[1]);
debug(`FileClient found '${extension}' extension`);
let contentType;
if (form.contentType) {
if (form.contentType != null) {
contentType = form.contentType;
} else {
// *guess* contentType based on file extension
Expand Down
5 changes: 1 addition & 4 deletions packages/binding-http/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
{
"extends": "../../.eslintrc.js",
"rules": {
"@typescript-eslint/strict-boolean-expressions": ["error"]
}
"extends": "../../.eslintrc.js"
}
2 changes: 1 addition & 1 deletion packages/binding-mbus/src/mbus-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ export default class MBusClient implements ProtocolClient {
throw new Error("Malformed form: offset must be defined");
}

result["mbus:timeout"] = form["mbus:timeout"] ? form["mbus:timeout"] : DEFAULT_TIMEOUT;
result["mbus:timeout"] = form["mbus:timeout"] ?? DEFAULT_TIMEOUT;

return result;
}
Expand Down
17 changes: 8 additions & 9 deletions packages/binding-mbus/src/mbus-connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,15 +132,14 @@ export class MBusConnection {
this.connecting = true;

for (let retry = 0; retry < this.config.maxRetries; retry++) {
if (
this.client.connect((err: string) => {
if (err != null) {
warn(
`Cannot connect to ${this.host}. Reason: ${err}. Retry in ${this.config.connectionRetryTime}ms.`
);
}
})
) {
const success: boolean = this.client.connect((err: string) => {
if (err != null) {
warn(
`Cannot connect to ${this.host}. Reason: ${err}. Retry in ${this.config.connectionRetryTime}ms.`
);
}
});
if (success) {
this.connecting = false;
this.connected = true;
debug(`MBus connected to ${this.host}`);
Expand Down
4 changes: 2 additions & 2 deletions packages/binding-mbus/test/mbus-client-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,12 @@ describe("mbus client test", () => {
// eslint-disable-next-line dot-notation
client["overrideFormFromURLPath"](form);
form["mbus:unitID"].should.be.equal(2, "Form value not overridden");
if (form["mbus:offset"]) {
if (form["mbus:offset"] != null) {
form["mbus:offset"].should.be.equal(2, "Form value not overridden");
} else {
expect.fail("mbus:offset undefined");
}
if (form["mbus:timeout"]) {
if (form["mbus:timeout"] != null) {
form["mbus:timeout"].should.be.equal(5, "Form value not overridden");
} else {
expect.fail("mbus:timeout undefined");
Expand Down
28 changes: 15 additions & 13 deletions packages/binding-modbus/src/modbus-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ export default class ModbusClient implements ProtocolClient {
const parsed = new URL(form.href);
const port = parsed.port ? parseInt(parsed.port, 10) : DEFAULT_PORT;
let body;
if (content) {
if (content != null) {
body = await content.toBuffer();
}
const formValidated = this.validateAndFillDefaultForm(form, body?.byteLength);
Expand All @@ -160,7 +160,7 @@ export default class ModbusClient implements ProtocolClient {
const host = parsed.hostname;
const hostAndPort = host + ":" + port;

if (body) {
if (body != null) {
this.validateBufferLength(formValidated, body);
}

Expand Down Expand Up @@ -189,13 +189,13 @@ export default class ModbusClient implements ProtocolClient {

private validateEndianness(form: ModbusForm): Endianness {
let endianness = Endianness.BIG_ENDIAN;
if (form.contentType) {
if (form.contentType != null) {
const contentValues: string[] = form.contentType.split(";") ?? [];
// Check endian-ness
const byteSeq = contentValues.find((value) => /^byteSeq=/.test(value));
if (byteSeq) {
if (byteSeq != null) {
const guessEndianness = Endianness[byteSeq.split("=")[1] as keyof typeof Endianness];
if (guessEndianness) {
if (guessEndianness != null) {
endianness = guessEndianness;
} else {
throw new Error("Malformed form: Content Type endianness is not valid");
Expand All @@ -213,15 +213,15 @@ export default class ModbusClient implements ProtocolClient {
input["modbus:address"] = parseInt(pathComp[2], 10) || input["modbus:address"];

const queryQuantity = query.get("quantity");
if (queryQuantity) {
if (queryQuantity != null) {
input["modbus:quantity"] = parseInt(queryQuantity, 10);
}
}

private validateBufferLength(form: ModbusFormWithDefaults, buffer: Buffer) {
const mpy = form["modbus:entity"] === "InputRegister" || form["modbus:entity"] === "HoldingRegister" ? 2 : 1;
const quantity = form["modbus:quantity"];
if (buffer && buffer.length !== mpy * quantity) {
if (buffer.length !== mpy * quantity) {
throw new Error(
"Content length does not match register / coil count, got " +
buffer.length +
Expand All @@ -241,11 +241,11 @@ export default class ModbusClient implements ProtocolClient {
// take over latest content of form into a new result set
const result: ModbusForm = { ...form };

if (!form["modbus:function"] && !form["modbus:entity"]) {
if (form["modbus:function"] == null && form["modbus:entity"] == null) {
throw new Error("Malformed form: modbus:function or modbus:entity must be defined");
}

if (form["modbus:function"]) {
if (form["modbus:function"] != null) {
// Convert string function to enums if defined
if (typeof form["modbus:function"] === "string") {
result["modbus:function"] = ModbusFunction[form["modbus:function"]];
Expand Down Expand Up @@ -294,16 +294,18 @@ export default class ModbusClient implements ProtocolClient {
throw new Error("Malformed form: address must be defined");
}

if (!form["modbus:quantity"] && contentLength === 0) {
const hasQuantity = form["modbus:quantity"] != null;

if (!hasQuantity && contentLength === 0) {
result["modbus:quantity"] = 1;
} else if (!form["modbus:quantity"] && contentLength > 0) {
} else if (!hasQuantity && contentLength > 0) {
const regSize =
result["modbus:entity"] === "InputRegister" || result["modbus:entity"] === "HoldingRegister" ? 2 : 1;
result["modbus:quantity"] = contentLength / regSize;
}

result["modbus:pollingTime"] = form["modbus:pollingTime"] ? form["modbus:pollingTime"] : DEFAULT_POLLING;
result["modbus:timeout"] = form["modbus:timeout"] ? form["modbus:timeout"] : DEFAULT_TIMEOUT;
result["modbus:pollingTime"] ??= DEFAULT_POLLING;
result["modbus:timeout"] ??= DEFAULT_TIMEOUT;

return result as ModbusFormWithDefaults;
}
Expand Down
26 changes: 15 additions & 11 deletions packages/binding-mqtt/src/mqtt-broker-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,8 @@ export default class MqttBrokerServer implements ProtocolServer {

this.brokerURI = config.uri;

if (config.selfHost) {
const selfHost = config.selfHost ?? false;
if (selfHost) {
this.hostedServer = Server({});
let server;
if (config.key) {
Expand Down Expand Up @@ -145,7 +146,8 @@ export default class MqttBrokerServer implements ProtocolServer {
const topic = encodeURIComponent(name) + "/properties/" + encodeURIComponent(propertyName);
const property = thing.properties[propertyName];

if (!property.writeOnly) {
const writeOnly: boolean = property.writeOnly ?? false;
if (!writeOnly) {
const href = this.brokerURI + "/" + topic;
const form = new TD.Form(href, ContentSerdes.DEFAULT);
form.op = ["readproperty", "observeproperty", "unobserveproperty"];
Expand All @@ -165,7 +167,8 @@ export default class MqttBrokerServer implements ProtocolServer {
};
thing.handleObserveProperty(propertyName, observeListener, { formIndex: property.forms.length - 1 });
}
if (!property.readOnly) {
const readOnly: boolean = property.readOnly ?? false;
if (!readOnly) {
const href = this.brokerURI + "/" + topic + "/writeproperty";
this.broker.subscribe(topic + "/writeproperty");
const form = new TD.Form(href, ContentSerdes.DEFAULT);
Expand Down Expand Up @@ -204,7 +207,7 @@ export default class MqttBrokerServer implements ProtocolServer {
return;
}

if (!content) {
if (content == null) {
warn(`MqttBrokerServer on port ${this.getPort()} cannot process data for Event ${eventName}`);
thing.handleUnsubscribeEvent(eventName, eventListener, { formIndex: event.forms.length - 1 });
return;
Expand Down Expand Up @@ -233,10 +236,10 @@ export default class MqttBrokerServer implements ProtocolServer {
// connecting to the actions
debug(`MqttBrokerServer at ${this.brokerURI} received message for '${receivedTopic}'`);
const thing = this.things.get(segments[this.THING_NAME_SEGMENT_INDEX]);
if (thing) {
if (thing != null) {
if (segments[this.INTERACTION_TYPE_SEGMENT_INDEX] === "actions") {
const action = thing.actions[segments[this.INTERACTION_NAME_SEGMENT_INDEX]];
if (action) {
if (action != null) {
this.handleAction(action, packet, payload, segments, thing);
return;
}
Expand All @@ -248,10 +251,10 @@ export default class MqttBrokerServer implements ProtocolServer {
) {
// connecting to the writeable properties
const thing = this.things.get(segments[this.THING_NAME_SEGMENT_INDEX]);
if (thing) {
if (thing != null) {
if (segments[this.INTERACTION_TYPE_SEGMENT_INDEX] === "properties") {
const property = thing.properties[segments[this.INTERACTION_NAME_SEGMENT_INDEX]];
if (property) {
if (property != null) {
this.handlePropertyWrite(property, packet, payload, segments, thing);
} // Property exists?
}
Expand Down Expand Up @@ -291,7 +294,7 @@ export default class MqttBrokerServer implements ProtocolServer {
thing
.handleInvokeAction(segments[this.INTERACTION_NAME_SEGMENT_INDEX], inputContent, options)
.then((output: unknown) => {
if (output) {
if (output != null) {
warn(
`MqttBrokerServer at ${this.brokerURI} cannot return output '${
segments[this.INTERACTION_NAME_SEGMENT_INDEX]
Expand All @@ -315,7 +318,8 @@ export default class MqttBrokerServer implements ProtocolServer {
segments: string[],
thing: ExposedThing
) {
if (!property.readOnly) {
const readOnly = property.readOnly ?? false;
if (!readOnly) {
const contentType = packet?.properties?.contentType ?? ContentSerdes.DEFAULT;

const options: InteractionOptions & { formIndex: number } = {
Expand Down Expand Up @@ -360,7 +364,7 @@ export default class MqttBrokerServer implements ProtocolServer {
}
}

if (removedThing) {
if (removedThing != null) {
info(`MqttBrokerServer succesfully destroyed '${removedThing.title}'`);
} else {
info(`MqttBrokerServer failed to destroy thing with thingId '${thingId}'`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ describe("MQTT client implementation", () => {
if (!eventReceived) {
eventReceived = true;
} else {
if (!x.data) {
if (x.data == null) {
done(new Error("No data received"));
return;
}
Expand Down Expand Up @@ -138,7 +138,7 @@ describe("MQTT client implementation", () => {
if (!eventReceived) {
eventReceived = true;
} else {
if (!x.data) {
if (x.data == null) {
done(new Error("No data received"));
return;
}
Expand Down
9 changes: 5 additions & 4 deletions packages/binding-netconf/src/async-node-netconf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,9 @@ export class Client {
username: credentials.username,
password: credentials?.password,
};
if (credentials.privateKey) {
this.routerParams.pkey = await fsPromises.readFile(credentials.privateKey, { encoding: "utf8" });
const privateKey = credentials?.privateKey;
if (privateKey != null) {
this.routerParams.pkey = await fsPromises.readFile(privateKey, { encoding: "utf8" });
}
}

Expand All @@ -96,7 +97,7 @@ export class Client {

this.router = new nodeNetconf.Client(this.routerParams);
this.router.open((err?: string) => {
if (err) {
if (err != null) {
reject(err);
} else {
debug(
Expand All @@ -117,7 +118,7 @@ export class Client {
payload?: unknown
): Promise<unknown> {
return new Promise((resolve, reject) => {
if (payload) {
if (payload != null) {
xpathQuery = xpath2json.addLeaves(xpathQuery, payload);
}
const objRequest = xpath2json.xpath2json(xpathQuery, NSs);
Expand Down
Loading