From 2ea6c2e3a8d1d44342490a0e2b23fb4e6720b6bb Mon Sep 17 00:00:00 2001 From: Joey Baker Date: Tue, 5 Jul 2016 18:33:03 -0700 Subject: [PATCH] Fix: include option api correction AFAIK, hapi-sequelize doesn't have a `request.models`, but it does have a `request.getDb()` method that has `models` on it. This calls that method to get the related models, but allows `request.models` to keep working for backward compatibility. --- src/crud.js | 2 ++ src/utils.js | 17 +++++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/crud.js b/src/crud.js index 2acf5eb..90eb484 100644 --- a/src/crud.js +++ b/src/crud.js @@ -31,6 +31,8 @@ export const list = (server, model) => { const include = parseInclude(request); const where = parseWhere(request); + if (include instanceof Error) return void reply(include); + const list = await model.findAll({ where, include, }); diff --git a/src/utils.js b/src/utils.js index 1393877..03f648a 100644 --- a/src/utils.js +++ b/src/utils.js @@ -1,18 +1,27 @@ -import { omit } from 'lodash'; +import { omit, identity } from 'lodash'; export const parseInclude = request => { const include = Array.isArray(request.query.include) ? request.query.include : [request.query.include]; + const noGetDb = typeof request.getDb !== 'function'; + const noRequestModels = !request.models; + + if (noGetDb && noRequestModels) { + return new Error('`request.getDb` or `request.models` are not defined. Be sure to load hapi-sequelize before hapi-sequelize-crud.'); + } + + const {models} = noGetDb ? request : request.getDb(); + return include.map(a => { - if (typeof a === 'string') return request.models[a]; + if (typeof a === 'string') return models[a]; if (a && typeof a.model === 'string' && a.model.length) { - a.model = request.models[a.model]; + a.model = models[a.model]; } return a; - }).filter(a => a); + }).filter(identity); }; export const parseWhere = request => {