Skip to content

Instantly share code, notes, and snippets.

@pixelcure
Created June 19, 2018 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pixelcure/5830d02b44821a8b5bbaaa6ccb6cc30f to your computer and use it in GitHub Desktop.
Save pixelcure/5830d02b44821a8b5bbaaa6ccb6cc30f to your computer and use it in GitHub Desktop.
TS CookieHelper Class
@TylerK
Copy link

TylerK commented Jun 19, 2018

This looks super helpful! Hope you don't mind, I cleaned it up a bit and will be integrating this into a project I'm working on :)

type CookieValue = number | string;
type Milliseconds = number;

interface Cookie {
  name?: string;
  value?: CookieValue;
  expires?: Milliseconds;
}

class CookieHelper {
  private DEFAULT_EXPIRY_TIME_MS = 24 * 60 * 60 * 1000;

  public set({ name, value, expires }: Cookie): void {
    const expiryTime = expires || this.DEFAULT_EXPIRY_TIME_MS;
    let date = new Date();
    date.setTime(date.getTime() + expiryTime);
    document.cookie = `${name}=${value};expires=${date.toUTCString()};path=/`;
  }

  public get({ name }: Cookie): string {
    const foundCookieByName = document.cookie
      .split(';')
      .filter(item => item.indexOf(`${name}=`) >= 0);
    const cookieExists = !!foundCookieByName.length;
    return cookieExists ? foundCookieByName[0].split('=')[1] : '';
  }

  public check({ name, value, expires }: Cookie): CookieValue {
    const cookieValue = this.get({ name });
    if (cookieValue !== '') {
      return cookieValue;
    }
    this.set({name, value, expires});
    return value;
  }
}

export default new CookieHelper();

... meanwhile ...

import Cookies from 'cookie-helper';

Cookies.set({ 
  name: 'glass_cage_of_emotion',
  value: 'milk was a bad choice', 
  expires: 9999999,
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment