1
Fork 0
mirror of https://github.com/Steffo99/sophon.git synced 2024-12-23 07:14:21 +00:00

🐛 Allow useViewSet and useManagedViewSet to return undefined

This commit is contained in:
Steffo 2021-10-12 04:03:03 +02:00
parent 3c0c8d1e73
commit 7c3eab6e60
Signed by: steffo
GPG key ID: 6965406171929D01
3 changed files with 123 additions and 27 deletions

View file

@ -10,7 +10,7 @@ import {ResourceRouter} from "./ResourceRouter"
export interface ViewSetRouterProps<Resource extends DjangoResource> { export interface ViewSetRouterProps<Resource extends DjangoResource> {
viewSet: ManagedViewSet<Resource>, viewSet?: ManagedViewSet<Resource>,
pathSegment: keyof ParsedPath, pathSegment: keyof ParsedPath,
pkKey: keyof Resource pkKey: keyof Resource
// Don't ever dream of typing this. // Don't ever dream of typing this.
@ -20,13 +20,17 @@ export interface ViewSetRouterProps<Resource extends DjangoResource> {
} }
export function ViewSetRouter<Resource extends DjangoResource>({viewSet, unselectedRoute, selectedRoute, pathSegment, pkKey}: ViewSetRouterProps<Resource>): JSX.Element { export function ViewSetRouter<Resource extends DjangoResource>({viewSet, unselectedRoute: UnselectedRoute, selectedRoute: SelectedRoute, pathSegment, pkKey}: ViewSetRouterProps<Resource>): JSX.Element {
const path = useSophonPath() const path = useSophonPath()
const pk = path?.[pathSegment] const pk = path?.[pathSegment]
const selection = pk ? viewSet.resources?.find(res => res.value[pkKey] === pk) : undefined
const UnselectedRoute = unselectedRoute if(viewSet === undefined) {
const SelectedRoute = selectedRoute return (
<Box>
<Loading text={"Connecting..."}/>
</Box>
)
}
// If an error happens, display it in a ErrorBox // If an error happens, display it in a ErrorBox
if(viewSet.error) { if(viewSet.error) {
@ -35,7 +39,7 @@ export function ViewSetRouter<Resource extends DjangoResource>({viewSet, unselec
) )
} }
// If the viewset is loading, display a loading message // If the viewset is still loading, display a loading message
if(viewSet.resources === null) { if(viewSet.resources === null) {
return ( return (
<Box> <Box>
@ -44,6 +48,8 @@ export function ViewSetRouter<Resource extends DjangoResource>({viewSet, unselec
) )
} }
const selection = pk ? viewSet.resources?.find(res => res.value[pkKey] === pk) : undefined
return ( return (
<ResourceRouter <ResourceRouter
selection={selection} selection={selection}

View file

@ -21,32 +21,88 @@ type ManagedActionDetails = (method: Axios.Method, act: string, data: any) => Pr
// Public interfaces // Public interfaces
/**
* A ViewSet managed by {@link ManagedViewSet}.
*/
export interface ManagedViewSet<Resource> { export interface ManagedViewSet<Resource> {
/**
* Whether the whole ViewSet is busy performing an operation (`refresh`, `create`, `command`) or not.
*/
busy: boolean, busy: boolean,
/**
* The last error that occourred during an operation "poisoning" the whole ViewSet (`refresh`).
*/
error: Error | null, error: Error | null,
/**
* The last error that occourred during an operation on the ViewSet (`create`, `command`).
*/
operationError: Error | null, operationError: Error | null,
/**
* The full array of the resources of the ViewSet.
*/
resources: ManagedResource<Resource>[] | null, resources: ManagedResource<Resource>[] | null,
/**
* The function to call to `refresh` the whole ViewSet (re-`list` all resources).
*/
refresh: ManagedRefresh, refresh: ManagedRefresh,
/**
* The function to call to `create` a new resource.
*/
create: ManagedCreate<Resource>, create: ManagedCreate<Resource>,
/**
* The function to call to run a `command` on the whole ViewSet.
*/
command: ManagedCommand, command: ManagedCommand,
} }
/**
* A single resource managed by {@link useManagedViewSet}.
*/
export interface ManagedResource<Resource> { export interface ManagedResource<Resource> {
/**
* The value of the resource.
*/
value: Resource, value: Resource,
/**
* Whether the resource is busy performing an operation (`update`, `destroy`, `action`) or not.
*/
busy: boolean, busy: boolean,
/**
* The last error that occourred during an operation on the resource.
*/
error: Error | null, error: Error | null,
/**
* The function to call to `update` the resource.
*/
update: ManagedUpdateDetails<Resource> update: ManagedUpdateDetails<Resource>
/**
* The function to call to `destroy` the resource.
*/
destroy: ManagedDestroyDetails destroy: ManagedDestroyDetails
/**
* The function to run an `action` on the resource.
*/
action: ManagedActionDetails, action: ManagedActionDetails,
} }
// Reducer state // Reducer state
/**
* State for {@link reducerManagedViewSet}.
*/
export interface ManagedReducerState<Resource> { export interface ManagedReducerState<Resource> {
firstRun: boolean, firstRun: boolean,
@ -61,6 +117,9 @@ export interface ManagedReducerState<Resource> {
} }
/**
* Action for {@link reducerManagedViewSet}.
*/
export interface ManagedReducerAction { export interface ManagedReducerAction {
type: `${"refresh" | "create" | "command" | "update" | "destroy" | "action"}.${"start" | "success" | "error"}`, type: `${"refresh" | "create" | "command" | "update" | "destroy" | "action"}.${"start" | "success" | "error"}`,
value?: any, value?: any,
@ -68,6 +127,9 @@ export interface ManagedReducerAction {
} }
/**
* Reducer for {@link useManagedViewSet}.
*/
function reducerManagedViewSet<Resource>(state: ManagedReducerState<Resource>, action: ManagedReducerAction): ManagedReducerState<Resource> { function reducerManagedViewSet<Resource>(state: ManagedReducerState<Resource>, action: ManagedReducerAction): ManagedReducerState<Resource> {
switch(action.type) { switch(action.type) {
@ -221,7 +283,16 @@ function reducerManagedViewSet<Resource>(state: ManagedReducerState<Resource>, a
} }
export function useManagedViewSet<Resource extends DjangoResource>(baseRoute: string, pkKey: keyof Resource, refreshOnMount: boolean = true): ManagedViewSet<Resource> { /**
* Hook that provides an high-level interface for interacting with a Django ViewSet ({@link ManagedViewSet}).
*
* Returns `undefined` outside an {@link InstanceProvider}.
*
* @param baseRoute - The path to the ViewSet with a trailing slash.
* @param pkKey - The key of the returned resource that represents the primary key.
* @param refreshOnMount - Whether `refresh` should be automatically called on initialization or not.
*/
export function useManagedViewSet<Resource extends DjangoResource>(baseRoute: string, pkKey: keyof Resource, refreshOnMount: boolean = true): ManagedViewSet<Resource> | undefined {
const viewset = const viewset =
useViewSet<Resource>(baseRoute) useViewSet<Resource>(baseRoute)
@ -250,7 +321,7 @@ export function useManagedViewSet<Resource extends DjangoResource>(baseRoute: st
let response: Resource[] let response: Resource[]
try { try {
response = await viewset.list() response = await viewset!.list()
} }
catch(err) { catch(err) {
@ -288,7 +359,7 @@ export function useManagedViewSet<Resource extends DjangoResource>(baseRoute: st
let response: Resource let response: Resource
try { try {
response = await viewset.create({data}) response = await viewset!.create({data})
} }
catch(err) { catch(err) {
@ -326,7 +397,7 @@ export function useManagedViewSet<Resource extends DjangoResource>(baseRoute: st
let response: Resource[] let response: Resource[]
try { try {
response = await viewset.command({url: `${baseRoute}${cmd}/`, data, method}) response = await viewset!.command({url: `${baseRoute}${cmd}/`, data, method})
} }
catch(err) { catch(err) {
@ -374,7 +445,7 @@ export function useManagedViewSet<Resource extends DjangoResource>(baseRoute: st
let response: Resource let response: Resource
try { try {
response = await viewset.update(pk, {data}) response = await viewset!.update(pk, {data})
} }
catch(err) { catch(err) {
@ -421,7 +492,7 @@ export function useManagedViewSet<Resource extends DjangoResource>(baseRoute: st
}) })
try { try {
await viewset.destroy(pk) await viewset!.destroy(pk)
} }
catch(err) { catch(err) {
@ -468,7 +539,7 @@ export function useManagedViewSet<Resource extends DjangoResource>(baseRoute: st
let response: Resource let response: Resource
try { try {
response = await viewset.action({url: `${baseRoute}${pk}/${act}/`, data, method}) response = await viewset!.action({url: `${baseRoute}${pk}/${act}/`, data, method})
} }
catch(err) { catch(err) {
@ -514,18 +585,35 @@ export function useManagedViewSet<Resource extends DjangoResource>(baseRoute: st
useEffect( useEffect(
() => { () => {
if(!refreshOnMount) return if(!refreshOnMount) {
if(!state.firstRun) return return
if(state.busy) return }
if(state.error) return if(!viewset) {
if(state.resources) return return
}
if(!state.firstRun) {
return
}
if(state.busy) {
return
}
if(state.error) {
return
}
if(state.resources) {
return
}
// noinspection JSIgnoredPromiseFromCall // noinspection JSIgnoredPromiseFromCall
refresh() refresh()
}, },
[refresh, state, refreshOnMount] [refresh, state, refreshOnMount],
) )
if(!viewset) {
return undefined
}
return { return {
busy: state.busy, busy: state.busy,
error: state.error, error: state.error,

View file

@ -78,20 +78,20 @@ export interface ViewSet<Resource> {
* *
* Useful for performing low-level operations on a ViewSet. * Useful for performing low-level operations on a ViewSet.
* *
* Returns `undefined` outside an {@link InstanceProvider}.
*
* @param baseRoute - The path to the ViewSet with a trailing slash. * @param baseRoute - The path to the ViewSet with a trailing slash.
*/ */
export function useViewSet<Resource>(baseRoute: string): ViewSet<Resource> { export function useViewSet<Resource>(baseRoute: string): ViewSet<Resource> | undefined {
const api = useAuthorizedAxios() const api = useAuthorizedAxios()
const command: ViewSetCommand<Resource> = const command: ViewSetCommand<Resource> =
React.useCallback( React.useCallback(
async (config) => { async (config) => {
if (!api) throw new Error("useViewSet called while the Sophon instance was undefined.")
let nextUrl: string | null = config.url let nextUrl: string | null = config.url
let resources: Resource[] = [] let resources: Resource[] = []
while(nextUrl !== null) { while(nextUrl !== null) {
const response: AxiosResponse<DjangoPage<Resource>> = await api.request<DjangoPage<Resource>>({...config, url: nextUrl}) const response: AxiosResponse<DjangoPage<Resource>> = await api!.request<DjangoPage<Resource>>({...config, url: nextUrl})
nextUrl = response.data.next nextUrl = response.data.next
resources = [...resources, ...response.data.results] resources = [...resources, ...response.data.results]
} }
@ -103,9 +103,7 @@ export function useViewSet<Resource>(baseRoute: string): ViewSet<Resource> {
const action: ViewSetAction<Resource> = const action: ViewSetAction<Resource> =
React.useCallback( React.useCallback(
async (config) => { async (config) => {
if (!api) throw new Error("useViewSet called while the Sophon instance was undefined.") const response = await api!.request<Resource>(config)
const response = await api.request<Resource>(config)
return response.data return response.data
}, },
[api] [api]
@ -151,5 +149,9 @@ export function useViewSet<Resource>(baseRoute: string): ViewSet<Resource> {
[action, baseRoute], [action, baseRoute],
) )
if(!api) {
return undefined
}
return {command, action, list, retrieve, create, update, destroy} return {command, action, list, retrieve, create, update, destroy}
} }