🔨 remove unsafe date parsing options from getGithubUserContribution ( thanks @Sutil )

This commit is contained in:
platane
2021-10-04 11:32:54 +02:00
committed by Platane
parent 859fd7a695
commit bedc8d0e31
3 changed files with 23 additions and 26 deletions

View File

@@ -4,7 +4,6 @@ const params = [
//
[{}, ""],
[{ year: 2017 }, "from=2017-01-01&to=2017-12-31"],
[{ from: new Date("2017-12-03") }, "from=2017-12-03"],
[{ from: "2017-12-03" }, "from=2017-12-03"],
[{ to: "2017-12-03" }, "to=2017-12-03"],
] as const;
@@ -16,5 +15,5 @@ params.forEach(([params, res]) =>
);
it("should fail if the date is in the future", () => {
expect(() => formatParams({ to: new Date() })).toThrow(Error);
expect(() => formatParams({ to: "9999-01-01" })).toThrow(Error);
});

View File

@@ -1,6 +1,4 @@
export type Options =
| { from?: string | Date; to?: string | Date }
| { year: number };
export type Options = { from?: string; to?: string } | { year: number };
export const formatParams = (options: Options = {}) => {
const sp = new URLSearchParams();
@@ -8,26 +6,18 @@ export const formatParams = (options: Options = {}) => {
const o: any = { ...options };
if ("year" in options) {
const from = new Date();
from.setFullYear(options.year);
from.setMonth(0);
from.setDate(1);
const to = new Date();
to.setFullYear(options.year);
to.setMonth(11);
to.setDate(31);
o.from = from;
o.to = to;
o.from = `${options.year}-01-01`;
o.to = `${options.year}-12-31`;
}
for (const s of ["from", "to"])
if (o[s]) {
const value = formatDate(o[s]);
const value = o[s];
if (value >= formatDate(new Date()))
throw new Error("cannot get contribution for date in the future");
throw new Error(
"Cannot get contribution for a date in the future.\nPlease limit your range to the current UTC day."
);
sp.set(s, value);
}
@@ -35,12 +25,10 @@ export const formatParams = (options: Options = {}) => {
return sp.toString();
};
const formatDate = (input: Date | string) => {
const d = new Date(input);
const year = d.getFullYear();
const month = d.getMonth() + 1;
const date = d.getDate();
const formatDate = (d: Date) => {
const year = d.getUTCFullYear();
const month = d.getUTCMonth() + 1;
const date = d.getUTCDate();
return [
year,

View File

@@ -5,8 +5,18 @@ import { formatParams, Options } from "./formatParams";
/**
* get the contribution grid from a github user page
*
* use options.from=YYYY-MM-DD options.to=YYYY-MM-DD to get the contribution grid for a specific time range
* or year=2019 as an alias for from=2019-01-01 to=2019-12-31
*
* otherwise return use the time range from today minus one year to today ( as seen in github profile page )
*
* @param userName github user name
* @param options set the time range: from / to or year
* @param options
*
* @example
* getGithubUserContribution("platane", { from: "2019-01-01", to: "2019-12-31" })
* getGithubUserContribution("platane", { year: 2019 })
*
*/
export const getGithubUserContribution = async (
userName: string,