Skip to content

Instantly share code, notes, and snippets.

@artello73
Forked from 3lpsy/account.ts
Created October 9, 2023 17:11
Show Gist options
  • Save artello73/0df48380d6361e6c2c3f820fecbf6d0f to your computer and use it in GitHub Desktop.
Save artello73/0df48380d6361e6c2c3f820fecbf6d0f to your computer and use it in GitHub Desktop.

Revisions

  1. @3lpsy 3lpsy created this gist Aug 2, 2021.
    58 changes: 58 additions & 0 deletions account.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    /*
    I recently jumped into svelte programming and wanted to create a class/singleton that could double as a reactive writable store.
    I did things very wrong until people on the discord confirmed how wrong my implementation was so I wanted to provide a simple example.
    So below is a simple account store you can use. I'm not sure if it's optimal or even correct, but it's better than my first attempt.
    Feel free to provide feedback.
    */
    ```

    import { writable } from "svelte/store";
    // fake stuff for example
    import {AuthUser, GuestUser, authService} from "./utils";

    export default class Account {
    public subscribe: Function;
    private _set: Function;
    private _update: Function;
    private authUser: AuthUser;
    private isAuthenticated: Boolean;

    constructor() {
    this.authUser = new GuestUser();
    this.isAuthenticated = false;
    let {subscribe, set, update} = writable(this);
    this.subscribe = ubscribe;
    this._set = set;
    this._update = update;
    }

    login(form: AuthForm): Boolean {
    return authService.login(form).then((authUser) => {
    this._update((that) => {
    that.authUser = authUser;
    that.isAuthenticated = true;
    return that;
    });
    return true;
    }).catch((e: InvalidLogin) => {
    this.clearUser();
    return false;
    });
    }
    clearUser(): Boolean {
    this._update((that) => {
    that.authUser = new GuestUser();
    thas.isAuthenticated = false;
    });
    return true;
    }
    }

    /*
    Then in your .svelte, you could import a singleton/instance of the above class and use it as a store:
    {#if $account.isAuthenticated }
    <p> User: $account.authUser.name </p>
    {:else}
    <p> Need to login </p
    {/if}
    */