Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fx: rearchitected app to remove excessive store usage #238

Merged
merged 5 commits into from
Feb 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions src/app.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
<html lang="en">

<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
%sveltekit.head%
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
%sveltekit.head%
</head>

<body
class="scrollbar-thin scrollbar-thumb-[#aeaeae] scrollbar-track-[#25252A] overflow-y-scroll scrollbar-thumb-rounded">
<div style="display: contents">%sveltekit.body%</div>
class="scrollbar-thin scrollbar-thumb-[#aeaeae] scrollbar-track-[#25252A] overflow-y-scroll scrollbar-thumb-rounded">
<div style="display: contents">%sveltekit.body%</div>
</body>

</html>
102 changes: 61 additions & 41 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,48 @@
import { redirect } from '@sveltejs/kit'
import { get } from 'svelte/store'
import { getUserDetails, userRole, currentUser } from '$lib/stores/authStore'
import { getUserRole, getRoles } from '$lib/stores/adminStore'
import { getRemoteConfigs, isMaintenanceModeEnabled } from '$lib/stores/remoteConfigStore'
import { redirect, type HandleFetch } from '@sveltejs/kit'
import { get as getWritableVal } from 'svelte/store'
import {
isMaintenanceModeEnabled,
isFeatureVideoResponsesEnabled,
isFeatureGroupChatEnabled,
isFeatureMintPageEnabled,
isFeaturePremiumPageEnabled
} from '$lib/stores/remoteConfigStore'
import { Authenticate } from '$lib/authentication/authentication'
import type { Handle } from '@sveltejs/kit'
import { env } from '$env/dynamic/public'
import {
isChannelPage,
userId as userIdWritable,
token as tokenWritable
} from '$lib/stores/helperStore'
import { get } from '$lib/api'
import { current_user, user_role } from '$lib/stores/authStore'

export const handle: Handle = async ({ event, resolve }) => {
const pathname = event.url.pathname
const userId = event.url.searchParams.get('userId') || event.cookies.get('userId') || ''
userIdWritable.set(userId)
let token = event.url.searchParams.get('token') || event.cookies.get('token') || ''
tokenWritable.set(token)
let user = get(currentUser),
role = get(userRole),

let user: any = event.locals.user?.user || '',
isBanned = false
const role = getWritableVal(user_role)

const remoteConfigs = await get('/remote-configs', { userId, token })
remoteConfigs.map((config: { flagKey: string; flagValue: boolean }) => {
if (config.flagKey === 'maintenance-mode') isMaintenanceModeEnabled.set(config.flagValue)
if (config.flagKey === 'feature-video-responses')
isFeatureVideoResponsesEnabled.set(config.flagValue)
if (config.flagKey === 'feature-group-chat') isFeatureGroupChatEnabled.set(config.flagValue)
if (config.flagKey === 'feature-mint-page') isFeatureMintPageEnabled.set(config.flagValue)
if (config.flagKey === 'feature-premium-page') isFeaturePremiumPageEnabled.set(config.flagValue)
})

await getRemoteConfigs()
const maintenance_mode = get(isMaintenanceModeEnabled) || false
const maintenance_mode = getWritableVal(isMaintenanceModeEnabled) || false

if (token && userId) {
if (!user) {
const response = await getUserDetails(token, userId)
const response = await get('/auth/me', { userId, token })
if (response) {
if (response.freshJwt) {
token = response.freshJwt
}
user = response
currentUser.set(user)
user = response.user
current_user.set(user)
}
}

Expand All @@ -48,19 +57,19 @@ export const handle: Handle = async ({ event, resolve }) => {
headers['x-api-key'] = env.PUBLIC_API_KEY
}

const all_roles = await getRoles(true, headers)
if (Array.isArray(all_roles)) {
const get_role = await getUserRole(true, headers)
if (get_role && get_role.role) {
role = all_roles.find((item) => {
return item._id == get_role.role
const allRoles = await get('/roles', headers)
if (Array.isArray(allRoles)) {
const userRole = await get('/roles/role-mapping', headers)
if (userRole && userRole.role) {
const usersRoleName = allRoles.find((item) => {
return item._id == userRole.role
})?.name

userRole.set(role)
user_role.set(usersRoleName)
}
}
} catch (e) {
console.log('something wrong', e)
} catch (err) {
console.log('something went wrong', err)
}
}

Expand All @@ -86,18 +95,14 @@ export const handle: Handle = async ({ event, resolve }) => {

if (user && user.isBanned) {
isBanned = true

const cookieItem = ['token', 'userId']
cookieItem.forEach((item) => {
event.cookies.set(item, '', {
path: '/',
expires: new Date(0)
})
})

currentUser.set(null)
userRole.set('user')

user_role.set('user')
event.locals['isBanned'] = isBanned
}

Expand All @@ -113,23 +118,38 @@ export const handle: Handle = async ({ event, resolve }) => {
throw redirect(302, '/maintenance')
}
} else {
console.log('pathname', pathname)
if (pathname.includes('/channel')) {
isChannelPage.set(false)
} else {
isChannelPage.set(false)
}
return await resolve(event)
}
}
throw redirect(302, '/browse')
}

export function handleError({ error }: { error: any }) {
export const handleError = ({ error }: { error: any }) => {
console.log('error', error)
// example integration with https://sentry.io/
// Sentry.captureException(error, { event, errorId });
return {
message: 'Whoops something wrong!'
message: 'Whoops something went wrong!'
}
}

export const handleFetch = (async ({
event,
request,
fetch
}: {
event: any
request: any
fetch: any
}) => {
if (request.url.startsWith(env.PUBLIC_API_URL)) {
request.headers['userId'] = event.locals.user.userId
if (env.PUBLIC_CROSS_ORIGIN === 'false') {
request.headers['authorization'] = event.locals.user.token
} else {
request.headers['x-api-key'] = env.PUBLIC_X_API_KEY
}
}

return fetch(request)
}) satisfies HandleFetch
58 changes: 58 additions & 0 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { error } from '@sveltejs/kit'
import { env } from '$env/dynamic/public'

const base = env.PUBLIC_API_URL

async function send({
method,
path,
data,
headers
}: {
method: string
path: string
data?: any
headers?: any
}) {
const opts: any = { method, headers: {} }

if (data) {
opts.headers['Content-Type'] = 'application/json'
opts.body = JSON.stringify(data)
}

// if headers sent manually
if (headers && headers.userId) {
opts.headers['userId'] = headers.userId
}

if (env.PUBLIC_CROSS_ORIGIN === 'false') {
opts.headers['authorization'] = headers.token
} else {
opts.headers['x-api-key'] = env.PUBLIC_X_API_KEY
}

const res = await fetch(`${base}/${path}`, opts)
if (res.ok || res.status === 422) {
const text = await res.text()
return text ? JSON.parse(text) : {}
}

return { error: res.status }
}

export function get(path: string, headers?: any) {
return send({ method: 'GET', path, headers })
}

export function del(path: string) {
return send({ method: 'DELETE', path })
}

export function post(path: string, data: any) {
return send({ method: 'POST', path, data })
}

export function put(path: string, data: any = {}) {
return send({ method: 'PUT', path, data })
}
110 changes: 0 additions & 110 deletions src/lib/components/Browse/Carousel.svelte

This file was deleted.

Loading