mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-04-23 17:18:32 +02:00
Request Inheritance (#209)
This commit is contained in:
46
src-web/hooks/useInheritedHeaders.ts
Normal file
46
src-web/hooks/useInheritedHeaders.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import type {
|
||||
Folder,
|
||||
GrpcRequest,
|
||||
HttpRequest,
|
||||
HttpRequestHeader,
|
||||
WebsocketRequest,
|
||||
Workspace,
|
||||
} from '@yaakapp-internal/models';
|
||||
import { foldersAtom, workspacesAtom } from '@yaakapp-internal/models';
|
||||
import { atom, useAtomValue } from 'jotai';
|
||||
|
||||
const ancestorsAtom = atom(function (get) {
|
||||
return [...get(foldersAtom), ...get(workspacesAtom)];
|
||||
});
|
||||
|
||||
export type HeaderModel = HttpRequest | GrpcRequest | WebsocketRequest | Folder | Workspace;
|
||||
|
||||
export function useInheritedHeaders(baseModel: HeaderModel | null) {
|
||||
const parents = useAtomValue(ancestorsAtom);
|
||||
|
||||
if (baseModel == null) return [];
|
||||
if (baseModel.model === 'workspace') return [];
|
||||
|
||||
const next = (child: HeaderModel): HttpRequestHeader[] => {
|
||||
// Short-circuit
|
||||
if (child.model === 'workspace') {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Recurse up the tree
|
||||
const parent = parents.find((p) => {
|
||||
if (child.folderId) return p.id === child.folderId;
|
||||
else return p.id === child.workspaceId;
|
||||
});
|
||||
|
||||
// Failed to find parent (should never happen)
|
||||
if (parent == null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const headers = next(parent);
|
||||
return [...headers, ...parent.headers];
|
||||
};
|
||||
|
||||
return next(baseModel);
|
||||
}
|
||||
Reference in New Issue
Block a user