Skip to content

Commit

Permalink
Return null instead of throwing when User Object attribute helper is …
Browse files Browse the repository at this point in the history
…called with invalid value
  • Loading branch information
adams85 committed Nov 15, 2023
1 parent fb7d7aa commit 57b008e
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions src/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,48 @@ import { isStringArray } from "./RolloutEvaluator";

export type WellKnownUserObjectAttribute = "Identifier" | "Email" | "Country";

type AttributeValue<T, U> = T extends U ? string : null;

/** User Object. Contains user attributes which are used for evaluating targeting rules and percentage options. */
export class User {
/**
* Converts the specified `Date` value to the format expected by datetime comparison operators (BEFORE/AFTER).
* @param date The `Date` value to convert.
* @returns The User Object attribute value in the expected format.
*/
static attributeValueFromDate(date: Date): string {
static attributeValueFromDate<T>(date: T): AttributeValue<T, Date> {
if (!(date instanceof Date)) {
throw new Error("Invalid 'date' value");
return null as AttributeValue<T, Date>;
}

const unixTimeSeconds = date.getTime() / 1000;
return unixTimeSeconds + "";
return (unixTimeSeconds + "") as AttributeValue<T, Date>;
}

/**
* Converts the specified `number` value to the format expected by number comparison operators.
* @param number The `number` value to convert.
* @returns The User Object attribute value in the expected format.
*/
static attributeValueFromNumber(number: number): string {
static attributeValueFromNumber<T>(number: T): AttributeValue<T, number> {
if (typeof number !== "number" || !isFinite(number)) {
throw new Error("Invalid 'date' value");
return null as AttributeValue<T, number>;
}

return number + "";
return (number + "") as (AttributeValue<T, number>);
}

/**
* Converts the specified `string` items to the format expected by array comparison operators (ARRAY CONTAINS ANY OF/ARRAY NOT CONTAINS ANY OF).
* @param items The `string` items to convert.
* @returns The User Object attribute value in the expected format.
*/
static attributeValueFromStringArray(...items: ReadonlyArray<string>): string {
static attributeValueFromStringArray<T>(...items: ReadonlyArray<T>): AttributeValue<T, string> {
if (!isStringArray(items)) {
throw new Error("Invalid 'items' value");
return null as AttributeValue<T, string>;
}

return JSON.stringify(items);
return JSON.stringify(items) as AttributeValue<T, string>;
}

constructor(
Expand Down

0 comments on commit 57b008e

Please sign in to comment.