2020-11-20 06:55:40 +13:00
|
|
|
import * as API from "../api"
|
2021-01-08 03:53:56 +13:00
|
|
|
import { writable, get } from "svelte/store"
|
|
|
|
import { builderStore } from "./builder"
|
2021-01-29 03:29:35 +13:00
|
|
|
import { TableNames } from "../constants"
|
2020-11-12 01:25:50 +13:00
|
|
|
|
2020-11-19 08:18:18 +13:00
|
|
|
const createAuthStore = () => {
|
2021-01-29 03:29:35 +13:00
|
|
|
const store = writable(null)
|
2020-11-12 01:25:50 +13:00
|
|
|
|
2021-01-29 03:29:35 +13:00
|
|
|
// Fetches the user object if someone is logged in and has reloaded the page
|
|
|
|
const fetchUser = async () => {
|
|
|
|
// Fetch the first user if inside the builder
|
|
|
|
if (get(builderStore).inBuilder) {
|
|
|
|
const users = await API.fetchTableData(TableNames.USERS)
|
|
|
|
if (!users.error && users[0] != null) {
|
|
|
|
store.set(users[0])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Or fetch the current user from localstorage in a real app
|
|
|
|
else {
|
2021-01-29 03:51:24 +13:00
|
|
|
const user = await API.fetchSelf()
|
|
|
|
store.set(user)
|
2021-01-29 03:29:35 +13:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-18 01:08:24 +13:00
|
|
|
return {
|
|
|
|
subscribe: store.subscribe,
|
2021-06-21 20:56:46 +12:00
|
|
|
actions: { fetchUser },
|
2020-11-12 01:25:50 +13:00
|
|
|
}
|
2020-11-18 01:08:24 +13:00
|
|
|
}
|
2020-11-12 01:25:50 +13:00
|
|
|
|
2020-11-19 08:18:18 +13:00
|
|
|
export const authStore = createAuthStore()
|