Inside Refactor: Extract Authenticated Query Factory

by Jule 53 views
Inside Refactor: Extract Authenticated Query Factory

Every authenticated React Query hook repeats a 5-line guard pattern: tsnqueryFn: async () => {n if (!deviceKid || !privateKey || !wasmCrypto) throw new Error('Not authenticated');n return someFn(deviceKid, privateKey, wasmCrypto, ...);n},nenabled: Boolean(deviceKid && privateKey && wasmCrypto),nnThis pattern repeats 64 lines across 5 files - clearly a DRY disaster. Enter makeAuthQuery(device, fn, ...args): a single factory call that returns both the secure queryFn and enabled status. nnTypeScript saves the day - generics preserve type safety, avoiding the mess of any or runtime errors. nnExample: tsnconst { queryFn, enabled } = makeAuthQuery('abc123', fetchData, opts);nnif (!enabled) console.log('User not verified');nawait queryFn();nnnBut there is a catch: deviceKid and privateKey must be passed correctly - no shortcuts. nnHidden detail: developers often assume authentication state is seamless, but real-world apps face stale tokens, missing keys, or async context loss. nnH3: Most forget that wasmCrypto integration must survive hook unmount - memory leaks creep in fast.nH3: Silent failures happen when deviceKid is falsy but not null - guard logic must be strict, not lenient.nH3: This factory works best when paired with a central auth context, not scattered logic.nnControversy: some dismiss the refactor as ‘too small,’ but 64 redundant lines cost development time and mental load. This isn’t trivial - it’s foundational.nnThe Bottom Line: Stop repeating the same guards. One factory, one pattern. Authenticity starts in the code.n