From 36cc68b933df78c678047c72ff95da4f1bca7eae Mon Sep 17 00:00:00 2001 From: Miguel Freitas Date: Thu, 17 Mar 2022 14:22:59 -0300 Subject: [PATCH] Add cookie utils to set and get the favoriteTeam - closes #103 (#106) --- app/constants.ts | 1 + app/cookies.ts | 21 +++++++++++++++++++++ app/types.ts | 4 ++++ 3 files changed, 26 insertions(+) create mode 100644 app/cookies.ts diff --git a/app/constants.ts b/app/constants.ts index 572fc82..21a6698 100644 --- a/app/constants.ts +++ b/app/constants.ts @@ -115,6 +115,7 @@ export const REGULAR_PERIOD_COUNT = 4 export const DATE_DISPLAY_FORMAT = 'dd MMMM yyyy' export const DATE_LINK_FORMAT = 'yyyyMMdd' export const EST_IANA_ZONE_ID = 'America/New_York' +export const ONE_YEAR_IN_SECONDS = 365 * 24 * 60 * 60 export const TIME_TO_REFETCH = 20000 // 20s export const TIME_TO_CACHE = 15 // 15s diff --git a/app/cookies.ts b/app/cookies.ts new file mode 100644 index 0000000..288448b --- /dev/null +++ b/app/cookies.ts @@ -0,0 +1,21 @@ +import { createCookie } from 'remix' + +import { Team, UserPreferences } from '~/types' + +import { ONE_YEAR_IN_SECONDS } from './constants' + +const userPrefsCookie = createCookie('user-prefs', { + maxAge: ONE_YEAR_IN_SECONDS, +}) + +export async function getUserPrefsCookie(request: Request) { + const cookie: UserPreferences = + (await userPrefsCookie.parse(request.headers.get('Cookie'))) || {} + return { + getFavoriteTeam: (): Team | undefined => cookie.favoriteTeam, + setFavoriteTeam: (team: Team) => { + cookie.favoriteTeam = team + }, + commitUserPrefs: () => userPrefsCookie.serialize(cookie), + } +} diff --git a/app/types.ts b/app/types.ts index 7c537c3..537cf9f 100644 --- a/app/types.ts +++ b/app/types.ts @@ -133,3 +133,7 @@ export type SocialMetas = { origin?: string image?: string } + +export type UserPreferences = { + favoriteTeam: Team | undefined +}