google-calendar-url
Version:
Generate shareable URLs for adding Google Calendar events
63 lines • 2.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.googleCalendarEventUrl = googleCalendarEventUrl;
exports.toGoogleCalendarDate = toGoogleCalendarDate;
/**
* Remove undefined props from object
*/
function clean(obj) {
return Object.entries(obj).reduce((acc, [key, val]) => {
return val ? { ...acc, [key]: val } : acc;
}, {});
}
const datePattern = /^\d{8}(T\d{6}Z?)?$/;
/**
* Generate a Google Calendar event URL
*/
function googleCalendarEventUrl(options) {
let start = "start" in options ? options.start : undefined;
start = start === null || start === void 0 ? void 0 : start.replace(/\:/g, "").replace(/\-/g, "");
let end = "end" in options ? options.end : undefined;
end = end === null || end === void 0 ? void 0 : end.replace(/\:/g, "").replace(/\-/g, "");
if (start && !end) {
throw new Error("`end` is required when `start` is provided");
}
if (!start && end) {
throw new Error("`start` is required when `end` is provided");
}
if (start && !datePattern.test(start)) {
throw new Error("`start` is malformed");
}
if (end && !datePattern.test(end)) {
throw new Error("`end` is malformed");
}
if (start && end && start.length !== end.length) {
throw new Error("`start` and `end` must be in the same format");
}
const searchParams = {
action: "TEMPLATE",
dates: start && end ? `${start}/${end}` : undefined,
text: options.title,
location: options.location,
details: options.details,
};
const urlSearchParams = new URLSearchParams(clean(searchParams));
return ("https://calendar.google.com/calendar/event?" + urlSearchParams.toString());
}
/** Convert a JS Date to a Google Calendar ready string */
function toGoogleCalendarDate(date, options) {
const { source, style } = options;
const pad = (n) => n.toString().padStart(2, "0");
const y = source === "utc" ? date.getUTCFullYear() : date.getFullYear();
const m = pad((source === "utc" ? date.getUTCMonth() : date.getMonth()) + 1);
const d = pad(source === "utc" ? date.getUTCDate() : date.getDate());
if (style === "allDay") {
return `${y}${m}${d}`;
}
const hh = pad(source === "utc" ? date.getUTCHours() : date.getHours());
const mm = pad(source === "utc" ? date.getUTCMinutes() : date.getMinutes());
const ss = pad(source === "utc" ? date.getUTCSeconds() : date.getSeconds());
const z = style === "instant" ? "Z" : "";
return `${y}${m}${d}T${hh}${mm}${ss}${z}`;
}
//# sourceMappingURL=index.js.map