|
|
@@ -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} |
|
|
*/ |