Skip to content

Commit d7501cd

Browse files
committed
[metrics] Fixes custom metrics type checking
1 parent ef1f72c commit d7501cd

File tree

3 files changed

+17
-8
lines changed

3 files changed

+17
-8
lines changed

packages/gephi-lite/src/core/metrics/edges/edgeScript.ts

+3-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import { isBoolean, isNumber, isString } from "lodash";
2-
1+
import { isScalar } from "../../../utils/check";
32
import { graphDatasetAtom } from "../../graph";
43
import { FullGraph } from "../../graph/types";
54
import { dataGraphToFullGraph } from "../../graph/utils";
@@ -36,8 +35,8 @@ export const edgeScript: Metric<{ edges: ["custom"] }> = {
3635
const id = fullGraph.edges()[0];
3736
const attributes = fullGraph.getEdgeAttributes(id);
3837
const result = fn(id, attributes, 0, fullGraph);
39-
if (!isNumber(result) && !isString(result) && !isBoolean(result))
40-
throw new Error("Function must returns a number or a string");
38+
if (!isScalar(result))
39+
throw new Error("Function must returns a number, a string, a boolean, null or undefined");
4140
},
4241
defaultValue: edgeMetricCustomFn,
4342
},

packages/gephi-lite/src/core/metrics/nodes/nodeScript.ts

+3-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import { isBoolean, isNumber, isString } from "lodash";
2-
1+
import { isScalar } from "../../../utils/check";
32
import { graphDatasetAtom } from "../../graph";
43
import { FullGraph } from "../../graph/types";
54
import { dataGraphToFullGraph } from "../../graph/utils";
@@ -36,8 +35,8 @@ export const nodeScript: Metric<{ nodes: ["custom"] }> = {
3635
const id = fullGraph.nodes()[0];
3736
const attributs = fullGraph.getNodeAttributes(id);
3837
const result = fn(id, attributs, 0, fullGraph);
39-
if (!isNumber(result) && !isString(result) && !isBoolean(result))
40-
throw new Error("Function must return either a number or a string");
38+
if (!isScalar(result))
39+
throw new Error("Function must returns a number, a string, a boolean, null or undefined");
4140
},
4241
defaultValue: nodeMetricCustomFn,
4342
},

packages/gephi-lite/src/utils/check.ts

+11
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,15 @@
1+
import { Scalar } from "@gephi/gephi-lite-sdk";
12
import checkIsUrl from "is-url";
3+
import { isNil } from "lodash";
4+
5+
const NON_NIL_SCALAR_TYPES = new Set(["boolean", "number", "string"]);
6+
7+
/**
8+
* Check if a value is a scalar value.
9+
*/
10+
export function isScalar(value: unknown): value is Scalar {
11+
return isNil(value) || NON_NIL_SCALAR_TYPES.has(typeof value);
12+
}
213

314
/**
415
* Check if a string is a valid url.

0 commit comments

Comments
 (0)