From 85e0af2e9dc418726f6dbc35620412b7e56a517f Mon Sep 17 00:00:00 2001 From: garrettmills Date: Sat, 8 Feb 2020 12:36:42 -0600 Subject: [PATCH] Add API endpoint to fetch menu item tree --- app/controllers/api/v1/Menu.controller.js | 36 +++++++++++++++++++++++ app/models/auth/User.model.js | 9 ++++++ app/routing/routers/api/v1.routes.js | 2 ++ 3 files changed, 47 insertions(+) create mode 100644 app/controllers/api/v1/Menu.controller.js diff --git a/app/controllers/api/v1/Menu.controller.js b/app/controllers/api/v1/Menu.controller.js new file mode 100644 index 0000000..b7e8daf --- /dev/null +++ b/app/controllers/api/v1/Menu.controller.js @@ -0,0 +1,36 @@ +const Controller = require('libflitter/controller/Controller') + +/* + * Menu Controller + * ------------------------------------------------------------- + * Put some description here! + */ +class Menu extends Controller { + static get services() { + return [...super.services, 'models'] + } + + async get_items(req, res) { + const root_page = await req.user.get_root_page() + const nodes = await this._build_menu_object(root_page) + return res.api(nodes) + } + + async _build_menu_object(parent_node, arr= []) { + const children = await this.models.get('api:Page').find({UUID: {$in: parent_node.ChildPageIds}}) + if ( children ) { + for ( const child of children ) { + arr.push({ + id: child.UUID, + name: child.Name, + children: await this._build_menu_object(child), + }) + } + } + + return arr + } + +} + +module.exports = exports = Menu diff --git a/app/models/auth/User.model.js b/app/models/auth/User.model.js index 1c92291..b808c31 100644 --- a/app/models/auth/User.model.js +++ b/app/models/auth/User.model.js @@ -6,12 +6,21 @@ const AuthUser = require('flitter-auth/model/User') * properties here as you need. */ class User extends AuthUser { + static get services() { + return [...super.services, 'models'] + } + static get schema() { return {...super.schema, ...{ // other schema fields here }} } + async get_root_page() { + const Page = this.models.get('api:Page') + return Page.findOne({OrgUserId: this._id, ParentId: '0'}) + } + // Other members and methods here } diff --git a/app/routing/routers/api/v1.routes.js b/app/routing/routers/api/v1.routes.js index 7ead9e4..3920ad5 100644 --- a/app/routing/routers/api/v1.routes.js +++ b/app/routing/routers/api/v1.routes.js @@ -39,6 +39,8 @@ const index = { '/hello_world': ['controller::api:v1:Misc.hello_world'], '/page/:PageId': ['controller::api:v1:Page.get_page'], '/page/:PageId/nodes': ['controller::api:v1:Page.get_nodes'], + + '/menu/items': ['controller::api:v1:Menu.get_items'], }, post: {