From d6323b7842cb0a40e6d891b8325fcf334ec961ae Mon Sep 17 00:00:00 2001 From: Andrew Dodson <947163+MrSwitch@users.noreply.github.com> Date: Thu, 23 Jan 2025 15:48:58 +0000 Subject: [PATCH] fix(handler): enable handlers to attach filters to the request, fixes #391 (#394) --- src/format_request.js | 13 +++++++++-- test/specs/format_request.spec.js | 37 +++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/src/format_request.js b/src/format_request.js index 812753a..930530e 100644 --- a/src/format_request.js +++ b/src/format_request.js @@ -392,12 +392,21 @@ async function format_request(options, dareInstance) { // Loop through the joins array if (joins.length) { // Loop through the joins and pass through the formatter - const a = joins.map(join_object => { + const a = joins.map(async join_object => { // Set the parent join_object.parent = options; // Format join... - return format_request(join_object, dareInstance); + const formatedObject = await format_request(join_object, dareInstance); + + // If this is present + if (formatedObject) { + // The handler may have assigned filters when their previously wasn't any + formatedObject.has_filter ||= Boolean(formatedObject.filter); + } + + return formatedObject; + }); // Add Joins diff --git a/test/specs/format_request.spec.js b/test/specs/format_request.spec.js index 896c09b..69949c2 100644 --- a/test/specs/format_request.spec.js +++ b/test/specs/format_request.spec.js @@ -1,4 +1,5 @@ import {expect} from 'chai'; +import assert from 'node:assert/strict'; import Dare from '../../src/index.js'; /* * Format Request @@ -827,6 +828,42 @@ describe('format_request', () => { expect(commentsJoin).to.not.have.property('filter'); }); + it('should allow nested children to assign filters', async () => { + const removed = {removed: false}; + + dare.options.method = method; + dare.options.models = { + users: { + schema: {}, + get(options) { + // Add a filter to users to only show user who haven't been removed + options.filter = removed; + }, + }, + comments: { + schema: { + // Join definition to users model + user_id: ['users.id'], + }, + }, + }; + + /** + * Run a setup whereby we call `users` tree from within the `comments` tree, but with no `users` filter + */ + const comments = await dare.format_request({ + method, + table: 'comments', + fields: ['name', {users: ['name']}], + }); + + /** + * Test that `has_filter` and `filter` have been assigned to the `users` tree + */ + assert.strictEqual(comments._joins.at(0).has_filter, true); + assert.deepStrictEqual(comments._joins.at(0).filter, removed); + }); + it('should await the response from a promise', () => { const msg = 'snap'; dare.options.method = method;