|
| 1 | +import type { HookContext } from "@feathersjs/feathers"; |
| 2 | +import { FROM_CLIENT_FOR_SERVER_DEFAULT_KEY } from "./common"; |
| 3 | + |
| 4 | +export function defineParamsForServer(keyToHide: string) { |
| 5 | + return function paramsForServer(...whitelist: string[]) { |
| 6 | + return <H extends HookContext>(context: H) => { |
| 7 | + // clone params on demand |
| 8 | + let clonedParams; |
| 9 | + |
| 10 | + Object.keys(context.params).forEach((key) => { |
| 11 | + if (key === "query") { |
| 12 | + return; |
| 13 | + } |
| 14 | + |
| 15 | + if (whitelist.includes(key)) { |
| 16 | + if (!clonedParams) { |
| 17 | + clonedParams = { |
| 18 | + ...context.params, |
| 19 | + query: { |
| 20 | + ...context.params.query, |
| 21 | + }, |
| 22 | + }; |
| 23 | + } |
| 24 | + |
| 25 | + if (!clonedParams.query[keyToHide]) { |
| 26 | + clonedParams.query[keyToHide] = {}; |
| 27 | + } |
| 28 | + |
| 29 | + clonedParams.query[keyToHide][key] = clonedParams[key]; |
| 30 | + delete clonedParams[key]; |
| 31 | + } |
| 32 | + }); |
| 33 | + |
| 34 | + if (clonedParams) { |
| 35 | + context.params = clonedParams; |
| 36 | + } |
| 37 | + |
| 38 | + return context; |
| 39 | + }; |
| 40 | + }; |
| 41 | +} |
| 42 | + |
| 43 | +/** |
| 44 | + * a hook to move params to query._$client |
| 45 | + * the server only receives 'query' from params. All other params are ignored. |
| 46 | + * So, to use `$populateParams` on the server, we need to move the params to query._$client |
| 47 | + * the server will move them back to params |
| 48 | + */ |
| 49 | +export const paramsForServer = defineParamsForServer( |
| 50 | + FROM_CLIENT_FOR_SERVER_DEFAULT_KEY, |
| 51 | +); |
| 52 | + |
| 53 | +if (import.meta.vitest) { |
| 54 | + const { it, expect } = import.meta.vitest; |
| 55 | + |
| 56 | + it("should move params to query._$client", () => { |
| 57 | + expect( |
| 58 | + paramsForServer( |
| 59 | + "a", |
| 60 | + "b", |
| 61 | + )({ |
| 62 | + params: { |
| 63 | + a: 1, |
| 64 | + b: 2, |
| 65 | + query: {}, |
| 66 | + }, |
| 67 | + } as HookContext), |
| 68 | + ).toEqual({ |
| 69 | + params: { |
| 70 | + query: { |
| 71 | + _$client: { |
| 72 | + a: 1, |
| 73 | + b: 2, |
| 74 | + }, |
| 75 | + }, |
| 76 | + }, |
| 77 | + }); |
| 78 | + }); |
| 79 | + |
| 80 | + it("should move params to query._$client and leave remaining", () => { |
| 81 | + expect( |
| 82 | + paramsForServer("a")({ |
| 83 | + params: { |
| 84 | + a: 1, |
| 85 | + b: 2, |
| 86 | + query: {}, |
| 87 | + }, |
| 88 | + } as HookContext), |
| 89 | + ).toEqual({ |
| 90 | + params: { |
| 91 | + b: 2, |
| 92 | + query: { |
| 93 | + _$client: { |
| 94 | + a: 1, |
| 95 | + }, |
| 96 | + }, |
| 97 | + }, |
| 98 | + }); |
| 99 | + }); |
| 100 | +} |
0 commit comments