1.0.4 • Published 2 years ago

@svetlokit/cookie-manager v1.0.4

Weekly downloads
-
License
-
Repository
github
Last release
2 years ago

@svetlokit/cookie-manager

Library for simple management cookies in your SvelteKit app

Getting Started

1. Types

Add to your App.d.ts cookieManager fields - ServerCookieManager for server side and BrowserCookieManager for browser

declare namespace App {
	 interface Locals {
		userid: string;
		cookieManager: import('@svetlokit/cookie-manager').ServerCookieManager;
	}

	interface Platform {}

	interface Session {}

	interface Stuff {
		cookieManager: import('@svetlokit/cookie-manager').BrowserCookieManager;
	}
}

2. Hooks

Add cookieManagerHook

import type { Handle } from '@sveltejs/kit';
import { sequence } from '@sveltejs/kit/hooks';
import { cookieManagerHook } from  '@svetlokit/cookie-manager';

export const handle: Handle = sequence(cookieManagerHook, ...);

3. Create adapter

Create adapter for your cookie. You can do it by extending `CookieAdapter'

import { CookieAdapter } from  '@svetlokit/cookie-manager';

export class DateAdapter extends CookieAdapter<Date> {
    public static serialize(value: Date): string {
        return value.toISOString();
    }
    public static parse(serializedValue: string): Date {
        return new Date(serializedValue);
    }

    public get isFuture(): boolean {
        return this.value?.getTime() > Date.now();
    }
}

4. Use adapters

import { CookieManager, CookieTextAdapter } from '@svetlokit/cookie-manager';
import type { RequestEvent, RequestHandler } from '@sveltejs/kit';
import { DateAdapter } from './date.adapter.ts';

export const get: RequestHandler = async (event: RequestEvent) => {
    const userAuthorizedAt: DateAdapter = event.locals.cookieManager.getAdapter(DateAdapter, 'date-authorize');
    ...
    userAuthorizedAt.update(new Date());
    ...
    ...
    ...
    const userRegisteredAt: DateAdapter = event.locals.cookieManager.getAdapter(DateAdapter, 'date-register');
    ...
};

5. Use in browser

Add to __layout.svelte

<script lang="ts" context="module">
	import type { Load } from '@sveltejs/kit';
	import { BrowserCookieManager } from '@svetlokit/cookie-manager';

	// see https://kit.svelte.dev/docs#loading
	export const load: Load = async ({ fetch }) => {
		return { 
			stuff: {
				cookieManager: new BrowserCookieManager()
			}
		}
	};
</script>

And in ither files you can get manager from page store

<script lang="ts">
	import { page } from '$app/stores';

	import { onMount } from 'svelte';

	onMount(() =>{
		console.log($page.stuff.cookieManager);
	})
</script>

Entities

CookieManager<Options>

Mediator between cookies and adapters.

Members

FieldsDescripton
public get(name: string): stringundefinedGet cookie by name

CookieAdapter<T>

Adapter for cookie, that keep value of some type (default - string). You can create it with CookieManager#getAdapter, or by new ... (in this case don't forget CookieAdapter#setManager. By defalut implementented CookieJSONAdapter<D> and CookieTextAdapter.
Example of implementing adapter:

interface ParsedUserInfo {
    name: string;
    endOfTrial: string;
}

export interface UserInfo {
    name: string;
    endOfTrial: Date;
}

export class UserInfo extends CookieAdapter<Date> {
    public static serialize(value: UserInfo): string {
        return JSON.stringify(value);
    }
    public static parse(serializedValue: string): UserInfo {
        try {
            const info = JSON.parse(serializedValue);
            if (typeof info === 'object') {
                return {
                    ...info,
                    endOfTrial: new Date(info.endOfTrial)
                };
            }
        } catch (e) { }

        return null;
    }

    public get trialEnded(): boolean {
        return this.value?.endOfTrial?.getTime() > Date.now();
    }

    public extendTrial(): void {
        if (this.value) {
            const endOfTrial: Date = new Date(this.value.endOfTrial);
            endOfTrial.setDate(endOfTrial.getDate() + 1);
            
            this.update({ ...this.value, endOfTrial });
        }
    }
}

public static serialize<T>(value: T): string

Function for serialization value of adapter to cookie string value

...
public static serialize(value: Date): string {
    return value.toISOString();
}
...

public static parse<T>(serializedValue: string): T

Function for pasring adapter value from cookie value

...
public static parse(serializedValue: string): Date {
    return new Date(serializedValue);
}
...

Members

FieldsDescripton
public readonly name: stringName of cookie
public initialValue?: stringInitial cookie value on adapter create moment
public get serializedValue(): stringSerialized current adapter value
public value: D = nullCurrent adapter value
protected manager?: CookieManagerManager, that gives initial value and saves updated value of this adapter
1.0.2

2 years ago

1.0.1

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.0

2 years ago

0.0.10

2 years ago

0.0.9

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago