Skip to content

Commit

Permalink
fix linting and good practices
Browse files Browse the repository at this point in the history
  • Loading branch information
zAlweNy26 committed Jul 18, 2024
1 parent 9b09146 commit 793ec31
Show file tree
Hide file tree
Showing 14 changed files with 59 additions and 63 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ jobs:
uses: actions/setup-node@v4
with:
node-version: 18.x
cache: "pnpm"
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
- name: 'TODO to Issue'
uses: 'alstr/todo-to-issue-action@v4'
uses: alstr/todo-to-issue-action@v4
with:
IDENTIFIERS: '[{"name": "FEATURE", "labels": ["enhancement"]}, {"name": "BUG", "labels": ["bug"]}]'
ISSUE_TEMPLATE: '**Describe the reason of this issue**\n{{ body }}\n\nThe issue is present here:\n\n{{ snippet }}'
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/develop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ jobs:
uses: actions/setup-node@v4
with:
node-version: 18.x
cache: "pnpm"
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
- name: Build static files
run: pnpm run build
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/playwright.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ jobs:
uses: actions/setup-node@v4
with:
node-version: 18.x
cache: "pnpm"
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
- name: Install Playwright Browsers
run: pnpx playwright install --with-deps
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/vitest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ jobs:
uses: actions/setup-node@v4
with:
node-version: 18.x
cache: "pnpm"
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
- name: Run Vitest tests
run: pnpm run unit
16 changes: 8 additions & 8 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions src/App.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
<script setup lang="ts">
</script>
<script setup lang="ts"></script>

<template>
<div
Expand Down
10 changes: 6 additions & 4 deletions src/services/ApiService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@ const getPort = () => {
* API client to make requests to the endpoints and passing the JWT for authentication.
* Start as null and is initialized by App.vue
*/
let apiClient: CatClient | undefined = undefined
export { apiClient }

export let apiClient: CatClient | undefined = undefined

/**
* Function to instantiate the API client with the JWT token
* @param credential The JWT token to pass to the API client
*/
export const instantiateApiClient = (credential: string | undefined) => {
apiClient = new CatClient({
baseUrl: window.location.hostname,
Expand All @@ -28,7 +30,7 @@ export const instantiateApiClient = (credential: string | undefined) => {
timeout: 15000,
instant: true,
ws: {
retries: 1000, // big number here because the count is cumulative (`retries` is not reset on connection)
retries: 5,
delay: 2000,
onFailed: () => {
console.error('Failed to connect WebSocket after several retries.')
Expand Down
4 changes: 2 additions & 2 deletions src/services/EmbedderConfigService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ import type { JSONSettings } from '@models/JSONSchema'
const EmbedderService = Object.freeze({
getEmbedders: async () => {
return await tryRequest(
apiClient.api?.embedder.getEmbeddersSettings(),
apiClient?.api?.embedder.getEmbeddersSettings(),
'Getting all the available embedders',
'Unable to get the list of available embedders',
)
},
setEmbedderSettings: async (languageEmbedderName: string, settings: JSONSettings) => {
return await tryRequest(
apiClient.api?.embedder.upsertEmbedderSetting(languageEmbedderName, settings),
apiClient?.api?.embedder.upsertEmbedderSetting(languageEmbedderName, settings),
'Language model embedder updated successfully',
"Language model embedder couldn't be updated",
'Sending the embedder settings to the cat',
Expand Down
4 changes: 2 additions & 2 deletions src/services/LLMConfigService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ import type { JSONSettings } from '@models/JSONSchema'
const LLMService = Object.freeze({
getProviders: async () => {
return await tryRequest(
apiClient.api?.llm.getLlmsSettings(),
apiClient?.api?.llm.getLlmsSettings(),
'Getting all the available providers',
'Unable to get the list of available providers',
)
},
setProviderSettings: async (languageModelName: string, settings: JSONSettings) => {
return await tryRequest(
apiClient.api?.llm.upsertLlmSetting(languageModelName, settings),
apiClient?.api?.llm.upsertLlmSetting(languageModelName, settings),
'Language model provider updated successfully',
"Language model provider couldn't be updated",
'Sending the language model settings to the cat',
Expand Down
14 changes: 7 additions & 7 deletions src/services/UserService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,41 +6,41 @@ import type { UserCreate, UserCredentials, UserUpdate } from 'ccat-api'
*/
const UserService = Object.freeze({
getUsers: async () => {
return await tryRequest(apiClient.api?.users.readUsers(), 'Getting all the users', 'Unable to fetch users')
return await tryRequest(apiClient?.api?.users.readUsers(), 'Getting all the users', 'Unable to fetch users')
},
getUser: async (id: string) => {
return await tryRequest(apiClient.api?.users.readUser(id), 'The selected user id does not exist', 'Unable to get the user')
return await tryRequest(apiClient?.api?.users.readUser(id), 'The selected user id does not exist', 'Unable to get the user')
},
impersonateUser: async (credentials: UserCredentials) => {
return await tryRequest(
apiClient.api?.userAuth.authToken(credentials),
apiClient?.api?.userAuth.authToken(credentials),
`Impersonating the user ${credentials.username}`,
`Unable to impersonate the user ${credentials.username}`,
)
},
getAvailablePermissions: async () => {
return await tryRequest(
apiClient.api?.userAuth.getAvailablePermissions(),
apiClient?.api?.userAuth.getAvailablePermissions(),
'Getting all the available permissions',
'Unable to fetch the available permissions',
)
},
createUser: async (user: UserCreate) => {
return await tryRequest(
apiClient.api?.users.createUser(user),
apiClient?.api?.users.createUser(user),
'All in-memory collections were wiped',
'Unable to wipe the in-memory collections',
)
},
updateUser: async (id: string, body: UserUpdate) => {
return await tryRequest(
apiClient.api?.users.updateUser(id, body),
apiClient?.api?.users.updateUser(id, body),
`The user ${id} was updated successfully`,
`Unable to update user ${id}`,
)
},
deleteUser: async (id: string) => {
return await tryRequest(apiClient.api?.users.deleteUser(id), `The user ${id} was deleted successfully`, `Unable to delete user ${id}`)
return await tryRequest(apiClient?.api?.users.deleteUser(id), `The user ${id} was deleted successfully`, `Unable to delete user ${id}`)
},
})

Expand Down
46 changes: 22 additions & 24 deletions src/stores/useMainStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { createMongoAbility } from '@casl/ability'
import { instantiateApiClient } from '@services/ApiService'
import LogService from '@services/LogService'


interface Filter {
[k: string]: {
values: string[]
Expand All @@ -25,38 +24,38 @@ type AuthToken = JwtPayload & {
* App wide store, containing info used in multiple views and components
*/
export const useMainStore = defineStore('main', () => {

/**
* Extract cookie from headers and JWT payload from it
*/
const cookies = useCookies(['ccat_user_token'], { doNotParse: true, autoUpdateDependencies: true })
const cookie = computed(() => cookies.get<string | undefined>('ccat_user_token'))
const cookie = computed({
get: () => cookies.get<string | undefined>('ccat_user_token'),
set: value => cookies.set('ccat_user_token', value),
})
const jwtPayload = computed(() => {
if (!cookie.value) return null
const { payload } = useJwt<AuthToken>(cookie.value)
return payload.value
})

/**
* User permissions
*/
const perms = useAbility()
if (jwtPayload.value){
instantiateApiClient(cookie.value)

perms.update(
createMongoAbility(
jwtPayload.value === null
? []
: Object.entries(jwtPayload.value.permissions).map(([subject, action]) => ({
subject,
action,
})),
).rules,
)
LogService.success(`Authenticated as ${jwtPayload.value.username}`)

}

tryOnBeforeMount(() => {
if (jwtPayload.value) {
instantiateApiClient(cookie.value)
perms.update(
createMongoAbility(
jwtPayload.value === null
? []
: Object.entries(jwtPayload.value.permissions).map(([subject, action]) => ({
subject,
action,
})),
).rules,
)
LogService.success(`Authenticated as ${jwtPayload.value.username}`)
}
})

/**
* Dark theme
*/
Expand Down Expand Up @@ -90,7 +89,6 @@ export const useMainStore = defineStore('main', () => {
toggleDark,
cookie,
jwtPayload,
perms
}
})

Expand Down
7 changes: 3 additions & 4 deletions src/stores/useMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { uniqueId } from 'lodash'
import { useNotifications } from '@stores/useNotifications'
import { apiClient } from '@services/ApiService'
import MemoryService from '@services/MemoryService'
import { useMainStore } from './useMainStore'

export const useMessages = defineStore('messages', () => {
const currentState = reactive<MessagesState>({
Expand Down Expand Up @@ -61,13 +60,13 @@ export const useMessages = defineStore('messages', () => {
if (apiClient?.socketState === WebSocket.OPEN) {
currentState.ready = true
}

/**
* Subscribes to the messages service on component mount
* and dispatches the received messages to the store.
* It also dispatches the error to the store if an error occurs.
*/
if(apiClient == undefined) {
*/
if (apiClient == undefined) {
return
}
apiClient
Expand Down
6 changes: 2 additions & 4 deletions src/stores/useUsers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const useUsers = defineStore('users', () => {
})

const { sendNotificationFromJSON } = useNotifications()
const { cookies } = useMainStore()
const { cookie } = storeToRefs(useMainStore())

const deleteUser = async (id: string) => {
currentState.loading = true
Expand All @@ -39,9 +39,7 @@ export const useUsers = defineStore('users', () => {
const impersonateUser = async (username: string, password: string) => {
currentState.loading = true
const result = await UserService.impersonateUser({ username, password })
if (result.status == 'success' && result.data) {
cookies.set('ccat_user_token', result.data.access_token)
}
if (result.status == 'success' && result.data) cookie.value = result.data.access_token
currentState.loading = false
return sendNotificationFromJSON(result)
}
Expand Down
2 changes: 1 addition & 1 deletion src/views/SettingsView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import SidePanel from '@components/SidePanel.vue'
import type { Status, UserResponse } from 'ccat-api'
const getStatus = async () => {
const result = await tryRequest(apiClient.api?.status.home(), 'Getting Cheshire Cat status', 'Unable to fetch Cheshire Cat status')
const result = await tryRequest(apiClient?.api?.status.home(), 'Getting Cheshire Cat status', 'Unable to fetch Cheshire Cat status')
return result.data
}
Expand Down

0 comments on commit 793ec31

Please sign in to comment.