Skip to content

Commit

Permalink
improve date parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
tobiasdiez committed Sep 23, 2023
1 parent 1d5b9e0 commit 72f6ae8
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 12 deletions.
53 changes: 43 additions & 10 deletions src/runtime/utils.azure.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type { Cookie } from "@azure/functions";
import { parse } from "cookie-es";
import { splitCookiesString } from "h3";
import { satisfies } from "semver";

export function getAzureParsedCookiesFromHeaders(
headers: Record<string, number | string | string[] | undefined>
Expand All @@ -16,17 +15,51 @@ export function getAzureParsedCookiesFromHeaders(
console.log(parse(cookie), cookie);
if (entries.length > 0) {
const [entry, ...rest] = entries;
return [
{
name: entry[0],
value: entry[1],
...Object.fromEntries(
rest.map(([key, value]) => [key.toLowerCase(), value])
),
},
];
const options = Object.fromEntries(
rest.map(([k, v]) => [k.toLowerCase(), v])
);
const res = {
name: entry[0],
value: entry[1],
domain: options.domain,
path: options.path,
expires: parseNumberOrDate(options.expires),
// secure: options.secure,
// httponly: options.httponly,
samesite: options.samesite,
maxAge: parseNumber(options.maxAge),
} as Cookie;
for (const key in res) {
if (res[key] === undefined) {
delete res[key];
}
}
return [res];
}
return [];
});
return cookies;
}

function parseNumberOrDate(expires: string) {
const expiresAsNumber = parseNumber(expires);
if (expiresAsNumber !== undefined) {
return expiresAsNumber;
}
// Convert to Date if possible
const expiresAsDate = new Date(expires);
if (!Number.isNaN(expiresAsDate.getTime())) {
return expiresAsDate;
}
}

function parseNumber(maxAge: string) {
if (!maxAge) {
return undefined;
}
// Convert to number if possible
const maxAgeAsNumber = Number(maxAge);
if (!Number.isNaN(maxAgeAsNumber)) {
return maxAgeAsNumber;
}
}
4 changes: 2 additions & 2 deletions test/unit/azure.utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ describe("getAzureParsedCookiesFromHeaders", () => {
{
name: "foo",
value: "bar",
expires: "Thu, 01 Jan 1970 00:00:00 GMT",
expires: new Date("1970-01-01T00:00:00.000Z"),
},
]);
});
Expand All @@ -47,7 +47,7 @@ describe("getAzureParsedCookiesFromHeaders", () => {
{
name: "session",
value: "xyz",
expires: "Sun, 24 Mar 2024 09:13:27 GMT",
expires: new Date("2024-03-24T09:13:27.000Z"),
path: "/",
// TODO: httponly: true,
samesite: "Strict",
Expand Down

0 comments on commit 72f6ae8

Please sign in to comment.