Skip to content

Commit

Permalink
add endsWith expiration to date conditions
Browse files Browse the repository at this point in the history
  • Loading branch information
david-crespo committed Feb 7, 2025
1 parent b843d30 commit 631261a
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 13 deletions.
11 changes: 10 additions & 1 deletion oxide-api/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,17 @@ export const mapObj =
return newObj;
};

const isoDateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z$/;

export const parseIfDate = (k: string | undefined, v: unknown) => {
if (typeof v === "string" && (k?.startsWith("time_") || k === "timestamp")) {
if (
typeof v === "string" &&
isoDateRegex.test(v) &&
(k?.startsWith("time_") ||
k?.endsWith("_time") ||
k?.endsWith("_expiration") ||
k === "timestamp")
) {
const d = new Date(v);
if (isNaN(d.getTime())) return v;
return d;
Expand Down
19 changes: 8 additions & 11 deletions oxide-openapi-gen-ts/src/client/static/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,17 +90,14 @@ describe("parseIfDate", () => {
expect(parseIfDate("abc", dateStr)).toEqual(dateStr);
});

it("parses dates if key starts with time_", () => {
const value = parseIfDate("time_whatever", dateStr);
expect(value).toBeInstanceOf(Date);
expect((value as Date).getTime()).toEqual(timestamp);
});

it("parses dates if key = 'timestamp'", () => {
const value = parseIfDate("timestamp", dateStr);
expect(value).toBeInstanceOf(Date);
expect((value as Date).getTime()).toEqual(timestamp);
});
it.each(["time_whatever", "auto_thing_expiration", "timestamp"])(
"parses dates if key is '%s'",
(key) => {
const value = parseIfDate(key, dateStr);
expect(value).toBeInstanceOf(Date);
expect((value as Date).getTime()).toEqual(timestamp);
}
);

it("passes through values that fail to parse as dates", () => {
const value = parseIfDate("time_whatever", "blah");
Expand Down
11 changes: 10 additions & 1 deletion oxide-openapi-gen-ts/src/client/static/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,17 @@ export const mapObj =
return newObj;
};

const isoDateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z$/;

export const parseIfDate = (k: string | undefined, v: unknown) => {
if (typeof v === "string" && (k?.startsWith("time_") || k === "timestamp")) {
if (
typeof v === "string" &&
isoDateRegex.test(v) &&
(k?.startsWith("time_") ||
k?.endsWith("_time") ||
k?.endsWith("_expiration") ||
k === "timestamp")
) {
const d = new Date(v);
if (isNaN(d.getTime())) return v;
return d;
Expand Down

0 comments on commit 631261a

Please sign in to comment.