Last active
October 5, 2022 19:13
-
-
Save sainf/06c4ed934f168c12c53187451f970f1f to your computer and use it in GitHub Desktop.
Use with feathers-mongo-aggregate easily
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// more info https://github.com/sainf/feathers-mongodb-aggregate | |
// | |
// To use on all / before | |
// | |
// This adds the array to params.aggregate to find and get. | |
// | |
// Strips data starts with "_l_" (lowercase L) on update and patch, useful for clear keys like lookups | |
// | |
// Example | |
// aggregate([ | |
// { | |
// $lookup: { | |
// from: 'storage', | |
// localField: '_id', | |
// foreignField: 'productId', | |
// as: '_l_stock', | |
// }, | |
// }, | |
// { | |
// ... | |
// }, | |
// ]), | |
import type { Hook, HookContext } from '@feathersjs/feathers' | |
import { MethodNotAllowed } from '@feathersjs/errors' | |
export default (options: any[]): Hook => { | |
return async (context: HookContext) => { | |
const { data, params, type, method } = context | |
if (!(type === 'before')) | |
throw new MethodNotAllowed('Only on type before') | |
if (method === 'find' || method === 'get') | |
params.aggregate = options | |
if (method === 'update' || method === 'patch') { | |
for (const [k] of Object.entries(data)) { | |
if (k.startsWith('_l_')) | |
delete data[k] | |
} | |
} | |
return context | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment