Hangar/frontend/store/index.ts

63 lines
2.4 KiB
TypeScript
Raw Normal View History

2021-02-03 07:47:15 +08:00
import { ActionTree, GetterTree, MutationTree } from 'vuex';
2021-01-23 03:20:03 +08:00
import { Context } from '@nuxt/types';
2021-01-23 15:37:57 +08:00
import { IPermission, IProjectCategory } from 'hangar-api';
import { NamedPermission, ProjectCategory } from '~/types/enums';
2021-01-23 03:20:03 +08:00
export const state = () => ({
projectCategories: (null as unknown) as Map<ProjectCategory, IProjectCategory>,
2021-01-23 15:37:57 +08:00
permissions: (null as unknown) as Map<NamedPermission, IPermission>,
2021-01-23 03:20:03 +08:00
});
export type RootState = ReturnType<typeof state>;
export const mutations: MutationTree<RootState> = {
SET_PROJECT_CATEGORIES: (state, payload: Map<ProjectCategory, IProjectCategory>) => {
state.projectCategories = payload;
},
2021-01-23 15:37:57 +08:00
SET_PERMISSIONS: (state, payload: Map<NamedPermission, IPermission>) => {
state.permissions = payload;
},
2021-01-23 03:20:03 +08:00
};
export const actions: ActionTree<RootState, RootState> = {
async nuxtServerInit({ commit }, { $api }: Context) {
try {
2021-02-03 07:47:15 +08:00
const categoryResult = await $api.requestInternal<IProjectCategory[]>('data/categories', false);
2021-01-23 03:20:03 +08:00
commit(
'SET_PROJECT_CATEGORIES',
convertToMap<ProjectCategory, IProjectCategory>(categoryResult, (value) => value.apiName)
);
2021-02-03 07:47:15 +08:00
const permissionResultTemp = await $api.requestInternal<{ value: string; frontendName: string; permission: string }[]>('data/permissions', false);
2021-01-23 15:37:57 +08:00
const permissionResult: IPermission[] = permissionResultTemp.map(({ value, frontendName, permission }) => ({
value,
frontendName,
permission: BigInt('0b' + permission),
}));
commit(
'SET_PERMISSIONS',
convertToMap<NamedPermission, IPermission>(permissionResult, (value) => value.value)
);
2021-01-23 03:20:03 +08:00
// others
} catch (e) {
2021-01-23 05:06:44 +08:00
console.error('ERROR FETCHING BACKEND DATA');
2021-01-23 03:20:03 +08:00
console.error(e);
}
},
};
2021-01-23 09:44:41 +08:00
export const getters: GetterTree<RootState, RootState> = {
visibleCategories: (state: RootState) => Array.from(state.projectCategories.values()).filter((value) => value.visible),
};
2021-01-23 03:20:03 +08:00
function convertToMap<E, T>(values: T[], toStringFunc: (value: T) => string): Map<E, T> {
const map = new Map<E, T>();
for (const value of values) {
2021-01-23 15:37:57 +08:00
const key: E = (toStringFunc(value) as unknown) as E;
if (key == null) {
throw new Error('Could not find an enum for ' + value);
}
map.set(key, value);
2021-01-23 03:20:03 +08:00
}
return map;
}