|
| 1 | +import { Signal, computed, inject } from "@angular/core"; |
| 2 | +import { SignalStoreFeature, patchState, signalStoreFeature, withMethods, withState } from "@ngrx/signals"; |
| 3 | +import { from, map, mergeMap, pipe, tap } from "rxjs"; |
| 4 | +import { rxMethod } from '@ngrx/signals/rxjs-interop'; |
| 5 | +import { isValidActionVerb } from "../util/is-valid-action-verb"; |
| 6 | +import { isValidHref } from "../util/is-valid-href"; |
| 7 | +import { RequestService } from "../services/request.service"; |
| 8 | +import { HateoasService } from "../services/hateoas.service"; |
| 9 | +import { defaultHypermediaActionState, HypermediaActionStateProps } from "./with-hypermedia-action"; |
| 10 | +import { Resource, ResourceAction } from "../models"; |
| 11 | + |
| 12 | +export type CollectionKey = string | number; |
| 13 | + |
| 14 | +export type HypermediaCollectionActionStateProps = { |
| 15 | + method: Record<CollectionKey, '' | 'PUT' | 'POST' | 'DELETE'> |
| 16 | + href: Record<CollectionKey, string> |
| 17 | + isAvailable: Record<CollectionKey, boolean> |
| 18 | + isExecuting: Record<CollectionKey, boolean> |
| 19 | + hasExecutedSuccessfully: Record<CollectionKey, boolean> |
| 20 | + hasExecutedWithError: Record<CollectionKey, boolean> |
| 21 | + hasError: Record<CollectionKey, boolean> |
| 22 | + error: Record<CollectionKey, unknown> |
| 23 | +} |
| 24 | + |
| 25 | +const defaultHypermediaCollectionActionState: HypermediaCollectionActionStateProps = { |
| 26 | + method: {}, |
| 27 | + href: {}, |
| 28 | + isAvailable: {}, |
| 29 | + isExecuting: {}, |
| 30 | + hasExecutedSuccessfully: {}, |
| 31 | + hasExecutedWithError: {}, |
| 32 | + hasError: {}, |
| 33 | + error: {} |
| 34 | +} |
| 35 | + |
| 36 | +export type HypermediaCollectionActionStoreState<ActionName extends string> = |
| 37 | +{ |
| 38 | + [K in `${ActionName}State`]: HypermediaCollectionActionStateProps |
| 39 | +}; |
| 40 | + |
| 41 | +export type ExecuteHypermediaCollectionActionMethod<ActionName extends string> = { |
| 42 | + [K in ActionName]: (id: CollectionKey) => Promise<void> |
| 43 | +}; |
| 44 | + |
| 45 | +export function generateExecuteHypermediaCollectionActionMethodName(actionName: string) { |
| 46 | + return actionName; |
| 47 | +} |
| 48 | + |
| 49 | +export type ConnectHypermediaCollectionActionMethod<ActionName extends string> = { |
| 50 | + [K in ActionName as `_connect${Capitalize<ActionName>}`]: (resourceLink: Signal<unknown[]>, idKeyName: string, action: string) => void |
| 51 | +}; |
| 52 | + |
| 53 | +export function generateConnectHypermediaCollectionActionMethodName(actionName: string) { |
| 54 | + return `_connect${actionName.charAt(0).toUpperCase() + actionName.slice(1)}`; |
| 55 | +} |
| 56 | + |
| 57 | +export type HypermediaCollectionActionMethods<ActionName extends string> = |
| 58 | + ExecuteHypermediaCollectionActionMethod<ActionName> & ConnectHypermediaCollectionActionMethod<ActionName> |
| 59 | + |
| 60 | +type ActionRxInput = { |
| 61 | + resource: Resource[], |
| 62 | + idLookup: (resource: Resource) => CollectionKey, |
| 63 | + action: string |
| 64 | +} |
| 65 | + |
| 66 | +function getState(store: unknown, stateKey: string): HypermediaCollectionActionStateProps { |
| 67 | + return (store as Record<string, Signal<HypermediaCollectionActionStateProps>>)[stateKey]() |
| 68 | +} |
| 69 | + |
| 70 | +function updateState(stateKey: string, partialState: Partial<HypermediaCollectionActionStateProps>) { |
| 71 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 72 | + return (state: any) => ({ [stateKey]: { ...state[stateKey], ...partialState } }); |
| 73 | +} |
| 74 | + |
| 75 | +function toResourceMap(resources: Resource[], idLookup: (resource: Resource) => CollectionKey): Record<CollectionKey, Resource> { |
| 76 | + const result: Record<CollectionKey, Resource> = {}; |
| 77 | + resources.forEach(resource => result[idLookup(resource)] = resource); |
| 78 | + return result; |
| 79 | +} |
| 80 | + |
| 81 | +function updateItemState(stateKey: string, id: CollectionKey, itemState: Partial<HypermediaActionStateProps> ) { |
| 82 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 83 | + return (state: { [K in any]: HypermediaCollectionActionStateProps}) => ({ [stateKey]: { |
| 84 | + href: itemState.href !== undefined ? { ...state[stateKey].href, [id]: itemState.href } : state[stateKey].href, |
| 85 | + method: itemState.method !== undefined ? { ...state[stateKey].method, [id]: itemState.method } : state[stateKey].method, |
| 86 | + isAvailable: itemState.isAvailable !== undefined ? { ...state[stateKey].isAvailable, [id]: itemState.isAvailable } : state[stateKey].isAvailable, |
| 87 | + isExecuting: itemState.isExecuting !== undefined ? { ...state[stateKey].isExecuting, [id]: itemState.isExecuting } : state[stateKey].isExecuting, |
| 88 | + hasExecutedSuccessfully: itemState.hasExecutedSuccessfully !== undefined ? { ...state[stateKey].hasExecutedSuccessfully, [id]: itemState.hasExecutedSuccessfully } : state[stateKey].hasExecutedSuccessfully, |
| 89 | + hasExecutedWithError: itemState.hasExecutedWithError !== undefined ? { ...state[stateKey].hasExecutedWithError, [id]: itemState.hasExecutedWithError } : state[stateKey].hasExecutedWithError, |
| 90 | + hasError: itemState.hasError !== undefined ? { ...state[stateKey].hasError, [id]: itemState.hasError } : state[stateKey].hasError, |
| 91 | + error: itemState.error !== undefined ? { ...state[stateKey].error, [id]: itemState.error } : state[stateKey].error |
| 92 | + } satisfies HypermediaCollectionActionStateProps |
| 93 | + }); |
| 94 | +} |
| 95 | + |
| 96 | +export function withHypermediaCollectionAction<ActionName extends string>( |
| 97 | + actionName: ActionName): SignalStoreFeature< |
| 98 | + { |
| 99 | + state: object; |
| 100 | + computed: Record<string, Signal<unknown>>; |
| 101 | + methods: Record<string, Function> |
| 102 | + }, |
| 103 | + { |
| 104 | + state: HypermediaCollectionActionStoreState<ActionName>; |
| 105 | + computed: Record<string, Signal<unknown>>; |
| 106 | + methods: HypermediaCollectionActionMethods<ActionName>; |
| 107 | + } |
| 108 | + >; |
| 109 | +export function withHypermediaCollectionAction<ActionName extends string>(actionName: ActionName) { |
| 110 | + |
| 111 | + const stateKey = `${actionName}State`; |
| 112 | + const executeMethodName = generateExecuteHypermediaCollectionActionMethodName(actionName); |
| 113 | + const connectMethodName = generateConnectHypermediaCollectionActionMethodName(actionName); |
| 114 | + |
| 115 | + return signalStoreFeature( |
| 116 | + withState({ |
| 117 | + [stateKey]: defaultHypermediaCollectionActionState |
| 118 | + }), |
| 119 | + withMethods((store, requestService = inject(RequestService)) => { |
| 120 | + |
| 121 | + const hateoasService = inject(HateoasService); |
| 122 | + let internalResourceMap: Signal<Record<CollectionKey, unknown>> | undefined; |
| 123 | + |
| 124 | + const rxConnectToResource = rxMethod<ActionRxInput>( |
| 125 | + pipe( |
| 126 | + tap(() => patchState(store, updateState(stateKey, defaultHypermediaCollectionActionState))), |
| 127 | + mergeMap(input => from(input.resource) |
| 128 | + .pipe( |
| 129 | + map(resource => [resource, hateoasService.getAction(resource, input.action)] satisfies [Resource, ResourceAction | undefined ] as [Resource, ResourceAction | undefined ]), |
| 130 | + map(([resource, action]) => { |
| 131 | + const actionState: HypermediaActionStateProps = defaultHypermediaActionState; |
| 132 | + if(action && isValidHref(action.href) && isValidActionVerb(action.method)) { |
| 133 | + actionState.href = action.href; |
| 134 | + actionState.method = action.method; |
| 135 | + actionState.isAvailable = true; |
| 136 | + } |
| 137 | + return [resource, actionState] satisfies [Resource, HypermediaActionStateProps] as [Resource, HypermediaActionStateProps]; |
| 138 | + }), |
| 139 | + tap(([resource, actionState]) => patchState(store, updateItemState(stateKey, input.idLookup(resource), actionState))) |
| 140 | + )) |
| 141 | + ) |
| 142 | + ); |
| 143 | + |
| 144 | + return { |
| 145 | + [executeMethodName]: async (id: CollectionKey): Promise<void> => { |
| 146 | + if(getState(store, stateKey).isAvailable[id] && internalResourceMap) { |
| 147 | + const method = getState(store, stateKey).method[id]; |
| 148 | + const href = getState(store, stateKey).href[id]; |
| 149 | + |
| 150 | + if(!method || !href) throw new Error('Action is not available'); |
| 151 | + |
| 152 | + const body = method !== 'DELETE' ? internalResourceMap()[id] : undefined |
| 153 | + |
| 154 | + patchState(store, |
| 155 | + updateItemState(stateKey, id, { |
| 156 | + isExecuting: true, |
| 157 | + hasExecutedSuccessfully: false, |
| 158 | + hasExecutedWithError: false, |
| 159 | + hasError: false, |
| 160 | + error: null |
| 161 | + })); |
| 162 | + |
| 163 | + try { |
| 164 | + await requestService.request(method, href, body); |
| 165 | + patchState(store, updateItemState(stateKey, id, { isExecuting: false, hasExecutedSuccessfully: true } )); |
| 166 | + } catch(e) { |
| 167 | + patchState(store, updateItemState(stateKey, id, { isExecuting: false, hasExecutedWithError: true, hasError: true, error: e } )); |
| 168 | + throw e; |
| 169 | + } |
| 170 | + } |
| 171 | + }, |
| 172 | + [connectMethodName]: (resourceLink: Signal<Resource[]>, idKeyName: string, action: string) => { |
| 173 | + if(!internalResourceMap) { |
| 174 | + const idLookup = (resource: Resource) => { |
| 175 | + const id = resource[idKeyName]; |
| 176 | + if(typeof id === 'string' || typeof id === 'number') return id; |
| 177 | + else throw new Error("The specified 'idKeyName' must point to a key with a value of type 'string' or 'number'"); |
| 178 | + }; |
| 179 | + internalResourceMap = computed(() => toResourceMap(resourceLink(), idLookup)); |
| 180 | + const input = computed(() => ({ resource: resourceLink(), idLookup, action })); |
| 181 | + rxConnectToResource(input); |
| 182 | + } |
| 183 | + } |
| 184 | + }; |
| 185 | + }) |
| 186 | + ); |
| 187 | +} |
0 commit comments