Derive initials from user names and email address

This commit is contained in:
Andrew Kingston 2021-05-21 13:17:09 +01:00
parent ce71ce1041
commit 4b106ace56
1 changed files with 27 additions and 10 deletions

View File

@ -1,25 +1,42 @@
import { writable } from "svelte/store" import { derived, writable } from "svelte/store"
import api from "../../builderStore/api" import api from "../../builderStore/api"
export function createAuthStore() { export function createAuthStore() {
const store = writable({ user: null }) const user = writable(null)
const store = derived(user, $user => {
let initials = null
if ($user) {
if ($user.firstName) {
initials = $user.firstName[0]
if ($user.lastName) {
initials += $user.lastName[0]
}
} else {
initials = $user.email[0]
}
}
return {
user: $user,
initials,
}
})
return { return {
subscribe: store.subscribe, subscribe: store.subscribe,
checkAuth: async () => { checkAuth: async () => {
const response = await api.get("/api/admin/users/self") const response = await api.get("/api/admin/users/self")
if (response.status !== 200) { if (response.status !== 200) {
store.update(state => ({ ...state, user: null })) user.set(null)
} else { } else {
const user = await response.json() const json = await response.json()
store.update(state => ({ ...state, user })) user.set(json)
} }
}, },
login: async creds => { login: async creds => {
const response = await api.post(`/api/admin/auth`, creds) const response = await api.post(`/api/admin/auth`, creds)
const json = await response.json() const json = await response.json()
if (response.status === 200) { if (response.status === 200) {
store.update(state => ({ ...state, user: json.user })) user.set(json.user)
} else { } else {
throw "Invalid credentials" throw "Invalid credentials"
} }
@ -31,12 +48,12 @@ export function createAuthStore() {
throw "Unable to create logout" throw "Unable to create logout"
} }
await response.json() await response.json()
store.update(state => ({ ...state, user: null })) user.set(null)
}, },
updateSelf: async user => { updateSelf: async newUser => {
const response = await api.post("/api/admin/users/self", user) const response = await api.post("/api/admin/users/self", newUser)
if (response.status === 200) { if (response.status === 200) {
store.update(state => ({ ...state, user: { ...state.user, ...user } })) user.update(state => ({ ...state, ...newUser }))
} else { } else {
throw "Unable to update user details" throw "Unable to update user details"
} }