Skip to content

Instantly share code, notes, and snippets.

@sainf
Last active October 5, 2022 19:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sainf/06c4ed934f168c12c53187451f970f1f to your computer and use it in GitHub Desktop.
Save sainf/06c4ed934f168c12c53187451f970f1f to your computer and use it in GitHub Desktop.
Use with feathers-mongo-aggregate easily
// 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