Guest User

Untitled

a guest
Nov 20th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. import {action, createAtom, IAtom} from 'mobx';
  2.  
  3. /**
  4. * Class wrapper for a single cookie entry
  5. * emitting to and reading from a cookie storage.
  6. */
  7. export class Cookie<T> {
  8. private atom: IAtom;
  9.  
  10. constructor (
  11. public readonly name: string,
  12. public readonly options: CookieOptions = {},
  13. private storage: ICookieMap
  14. ) {
  15. this.atom = createAtom('cookie-' + name);
  16. }
  17.  
  18. @action
  19. set (value: T) {
  20. if (value === undefined) {
  21. this.remove();
  22. } else {
  23. this.storage.set(this.name, JSON.stringify(value), this.options);
  24. this.atom.reportChanged();
  25. }
  26. }
  27.  
  28. get (): T {
  29. this.atom.reportObserved();
  30. const raw = this.storage.get(this.name);
  31. return raw && JSON.parse(raw);
  32. }
  33.  
  34. @action
  35. remove () {
  36. this.storage.delete(this.name);
  37. this.atom.reportChanged();
  38. }
  39. }
  40.  
  41. /**
  42. * Standard cookie options
  43. */
  44. export type CookieOptions = Partial<{
  45. expires: number,
  46. path: string,
  47. domain: string,
  48. secure: boolean
  49. }>;
  50.  
  51. /**
  52. * The implementation of this interface should write to
  53. * the environments cookie storage,ie. document.cookie.
  54. */
  55. export interface ICookieMap {
  56. set (name: string, value: string, options: CookieOptions): void;
  57. get (name: string): string;
  58. delete (name: string): void;
  59. }
  60.  
  61. const decoratorCookies = new Map<string, Cookie<any>>();
  62.  
  63. /**
  64. * Property decorator for automatically binding a property to a cookie of the same name
  65. */
  66. export function cookie (defaultValue?: any, options?: CookieOptions) {
  67. return function bake <T extends {map: ICookieMap}, V> (
  68. targetClass: T,
  69. propertyKey: keyof T
  70. ): void {
  71. function pull (targetInstance: T) {
  72. let cookie: Cookie<V> = decoratorCookies.get(propertyKey);
  73. if (!cookie) {
  74. cookie = new Cookie<V>(propertyKey, options, targetInstance.map);
  75. if (defaultValue !== undefined && cookie.get() === undefined) {
  76. cookie.set(defaultValue);
  77. }
  78. decoratorCookies.set(propertyKey, cookie);
  79. }
  80. return cookie;
  81. }
  82.  
  83. Object.defineProperty(targetClass, propertyKey, {
  84. get: function () { // tslint:disable-line
  85. return pull(this).get();
  86. },
  87. set: function (value: V) { // tslint:disable-line
  88. pull(this).set(value);
  89. }
  90. });
  91. };
  92. }
Add Comment
Please, Sign In to add comment