1 Commits

Author SHA1 Message Date
9a231f0685 2.6.1 2016-09-08 13:22:29 -07:00
10 changed files with 101 additions and 921 deletions

View File

@ -10,5 +10,5 @@
"transform-decorators-legacy", "transform-decorators-legacy",
"transform-es2015-modules-commonjs" "transform-es2015-modules-commonjs"
], ],
"sourceMaps": "inline" "sourceMaps": true
} }

3
.gitignore vendored
View File

@ -33,6 +33,3 @@ node_modules
# Debug log from npm # Debug log from npm
npm-debug.log npm-debug.log
# System
.DS_Store

View File

@ -9,7 +9,7 @@ This plugin depends on [`hapi-sequelize`](https://github.com/danecando/hapi-sequ
npm install -S hapi-sequelize-crud npm install -S hapi-sequelize-crud
``` ```
## Configure ##Configure
Please note that you should register `hapi-sequelize-crud` after defining your Please note that you should register `hapi-sequelize-crud` after defining your
associations. associations.
@ -52,20 +52,6 @@ await register({
// `config` if provided, overrides the default config // `config` if provided, overrides the default config
{model: 'bat', methods: ['list'], config: { ... }}, {model: 'bat', methods: ['list'], config: { ... }},
{model: 'bat', methods: ['create']} {model: 'bat', methods: ['create']}
{model: 'fly', config: {
// interact with the request before hapi-sequelize-crud does
, ext: {
onPreHandler: (request, reply) => {
if (request.auth.hasAccessToFly) reply.continue()
else reply(Boom.unauthorized())
}
}
// change the response data
response: {
schema: {id: joi.string()},
modify: true
}
}}
] ]
} }
}); });
@ -124,69 +110,6 @@ If you want to get multiple related models, just pass multiple `include` paramet
Team.findAll({include: [City, Uniform]}) Team.findAll({include: [City, Uniform]})
``` ```
## `limit` and `offset` queries
Restricting list (`GET`) and scope queries to a restricted count can be done by passing `limit=<number>` and/or `offset=<number>`.
```js
// returns 10 teams starting from the 10th
// GET /teams?limit=10&offset=10
// results in a Sequelize query:
Team.findAll({limit: 10, offset: 10})
```
## `order` queries
You can change the order of the resulting query by passing `order` to the query.
```js
// returns the teams ordered by the name column
// GET /teams?order[]=name
// results in a Sequelize query:
Team.findAll({order: ['name']})
```
```js
// returns the teams ordered by the name column, descending
// GET /teams?order[0]=name&order[0]=DESC
// results in a Sequelize query:
Team.findAll({order: [['name', 'DESC']]})
```
```js
// returns the teams ordered by the name, then the city columns, descending
// GET /teams?order[0]=name&order[1]=city
// results in a Sequelize query:
Team.findAll({order: [['name'], ['city']]})
```
## Authorization and other hooks
You can use Hapi's [`ext` option](http://hapijs.com/api#route-options) to interact with the request both before and after this module does. This is useful if you want to enforce authorization, or modify the request before or after this module does. Hapi [has a full list of hooks](http://hapijs.com/api#request-lifecycle) you can use.
## Modify the response format
By default, `hapi-sequelize-crud` routes will respond with the full model. You can modify this using the built-in [hapi settings](http://hapijs.com/tutorials/validation#output).
```js
await register({
register: require('hapi-sequelize-crud'),
options: {
{model: 'fly', config: {
response: {
// setting this schema will restrict the response to only the id
schema: { id: joi.string() },
// This tells Hapi to restrict the response to the keys specified in `schema`
modify: true
}
}}
}
})
```
## Full list of methods ## Full list of methods
Let's say you have a `many-to-many` association like this: Let's say you have a `many-to-many` association like this:

View File

@ -1,6 +1,6 @@
{ {
"name": "hapi-sequelize-crud", "name": "hapi-sequelize-crud",
"version": "2.7.0", "version": "2.6.1",
"description": "Hapi plugin that automatically generates RESTful API for CRUD", "description": "Hapi plugin that automatically generates RESTful API for CRUD",
"main": "build/index.js", "main": "build/index.js",
"config": { "config": {
@ -10,8 +10,8 @@
}, },
"scripts": { "scripts": {
"lint": "eslint src", "lint": "eslint src",
"test": "ava --require babel-register --source='src/**/*.js' --source='!build/**/*' --tap=${CI-false} src/**/*.test.js | $(if [ -z ${CI:-} ]; then echo 'tail'; else tap-xunit > $CIRCLE_TEST_REPORTS/ava/ava.xml; fi;)", "test": "ava --require babel-register --source='*.test.js' --tap=${CI-false} | $(if [ -z ${CI:-} ]; then echo 'tail'; else tap-xunit > $CIRCLE_TEST_REPORTS/ava/ava.xml; fi;)",
"tdd": "ava --require babel-register --source='src/**/*.js' --source='!build/**/*' --watch src/**/*.test.js", "tdd": "ava --require babel-register --source='*.test.js' --watch",
"build": "scripty", "build": "scripty",
"watch": "scripty" "watch": "scripty"
}, },
@ -25,26 +25,25 @@
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"ava": "^0.16.0", "ava": "^0.16.0",
"babel-cli": "^6.16.0", "babel-cli": "^6.14.0",
"babel-plugin-add-module-exports": "^0.2.1", "babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-closure-elimination": "^1.0.6", "babel-plugin-closure-elimination": "^1.0.6",
"babel-plugin-transform-decorators-legacy": "^1.3.4", "babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-plugin-transform-es2015-modules-commonjs": "^6.16.0", "babel-plugin-transform-es2015-modules-commonjs": "^6.14.0",
"babel-preset-stage-1": "^6.16.0", "babel-preset-stage-1": "^6.13.0",
"babel-register": "^6.16.3", "eslint": "^3.4.0",
"eslint": "^3.8.1",
"eslint-config-pichak": "^1.1.2", "eslint-config-pichak": "^1.1.2",
"eslint-plugin-ava": "^3.1.1", "eslint-plugin-ava": "^3.0.0",
"ghooks": "^1.3.2", "ghooks": "^1.3.2",
"scripty": "^1.6.0", "scripty": "^1.6.0",
"sinon": "^1.17.6", "sinon": "^1.17.5",
"sinon-bluebird": "^3.1.0", "sinon-bluebird": "^3.0.2",
"tap-xunit": "^1.4.0" "tap-xunit": "^1.4.0"
}, },
"dependencies": { "dependencies": {
"boom": "^4.2.0", "boom": "^4.0.0",
"joi": "^9.2.0", "joi": "^9.0.4",
"lodash": "^4.16.4" "lodash": "^4.15.0"
}, },
"optionalDependencies": { "optionalDependencies": {
"babel-polyfill": "^6.13.0" "babel-polyfill": "^6.13.0"

View File

@ -2,7 +2,7 @@ import joi from 'joi';
import path from 'path'; import path from 'path';
import error from './error'; import error from './error';
import _ from 'lodash'; import _ from 'lodash';
import { parseInclude, parseWhere, parseLimitAndOffset, parseOrder } from './utils'; import { parseInclude, parseWhere } from './utils';
import { notFound } from 'boom'; import { notFound } from 'boom';
import * as associations from './associations/index'; import * as associations from './associations/index';
import getConfigForMethod from './get-config-for-method.js'; import getConfigForMethod from './get-config-for-method.js';
@ -14,7 +14,6 @@ const createAll = ({
config, config,
attributeValidation, attributeValidation,
associationValidation, associationValidation,
scopes,
}) => { }) => {
Object.keys(methods).forEach((method) => { Object.keys(methods).forEach((method) => {
methods[method]({ methods[method]({
@ -26,7 +25,6 @@ const createAll = ({
attributeValidation, attributeValidation,
associationValidation, associationValidation,
config, config,
scopes,
}), }),
}); });
}); });
@ -66,8 +64,6 @@ export default (server, model, { prefix, defaultConfig: config, models: permissi
include: joi.array().items(joi.string().valid(...modelAssociations)), include: joi.array().items(joi.string().valid(...modelAssociations)),
}; };
const scopes = Object.keys(model.options.scopes);
// if we don't have any permissions set, just create all the methods // if we don't have any permissions set, just create all the methods
if (!permissions) { if (!permissions) {
createAll({ createAll({
@ -77,7 +73,6 @@ export default (server, model, { prefix, defaultConfig: config, models: permissi
config, config,
attributeValidation, attributeValidation,
associationValidation, associationValidation,
scopes,
}); });
// if permissions are set, but we can't parse them, throw an error // if permissions are set, but we can't parse them, throw an error
} else if (!Array.isArray(permissions)) { } else if (!Array.isArray(permissions)) {
@ -92,7 +87,6 @@ export default (server, model, { prefix, defaultConfig: config, models: permissi
config, config,
attributeValidation, attributeValidation,
associationValidation, associationValidation,
scopes,
}); });
// if we've gotten here, we have complex permissions and need to set them // if we've gotten here, we have complex permissions and need to set them
} else { } else {
@ -114,7 +108,6 @@ export default (server, model, { prefix, defaultConfig: config, models: permissi
method, method,
attributeValidation, attributeValidation,
associationValidation, associationValidation,
scopes,
config: permissionConfig, config: permissionConfig,
}), }),
}); });
@ -126,7 +119,6 @@ export default (server, model, { prefix, defaultConfig: config, models: permissi
prefix, prefix,
attributeValidation, attributeValidation,
associationValidation, associationValidation,
scopes,
config: permissionConfig, config: permissionConfig,
}); });
} }
@ -144,13 +136,11 @@ export const list = ({ server, model, prefix = '/', config }) => {
async handler(request, reply) { async handler(request, reply) {
const include = parseInclude(request); const include = parseInclude(request);
const where = parseWhere(request); const where = parseWhere(request);
const { limit, offset } = parseLimitAndOffset(request);
const order = parseOrder(request);
if (include instanceof Error) return void reply(include); if (include instanceof Error) return void reply(include);
const list = await model.findAll({ const list = await model.findAll({
where, include, limit, offset, order, where, include,
}); });
reply(list.map((item) => item.toJSON())); reply(list.map((item) => item.toJSON()));
@ -180,11 +170,19 @@ export const get = ({ server, model, prefix = '/', config }) => {
reply(instance.toJSON()); reply(instance.toJSON());
}, },
config, config: _.defaultsDeep(config, {
validate: {
params: {
id: joi.any(),
},
},
}),
}); });
}; };
export const scope = ({ server, model, prefix = '/', config }) => { export const scope = ({ server, model, prefix = '/', config }) => {
const scopes = Object.keys(model.options.scopes);
server.route({ server.route({
method: 'GET', method: 'GET',
path: path.join(prefix, model._plural, '{scope}'), path: path.join(prefix, model._plural, '{scope}'),
@ -193,18 +191,20 @@ export const scope = ({ server, model, prefix = '/', config }) => {
async handler(request, reply) { async handler(request, reply) {
const include = parseInclude(request); const include = parseInclude(request);
const where = parseWhere(request); const where = parseWhere(request);
const { limit, offset } = parseLimitAndOffset(request);
const order = parseOrder(request);
if (include instanceof Error) return void reply(include); if (include instanceof Error) return void reply(include);
const list = await model.scope(request.params.scope).findAll({ const list = await model.scope(request.params.scope).findAll({ include, where });
include, where, limit, offset, order,
});
reply(list.map((item) => item.toJSON())); reply(list.map((item) => item.toJSON()));
}, },
config, config: _.defaultsDeep(config, {
validate: {
params: {
scope: joi.string().valid(...scopes),
},
},
}),
}); });
}; };
@ -268,6 +268,8 @@ export const destroyAll = ({ server, model, prefix = '/', config }) => {
}; };
export const destroyScope = ({ server, model, prefix = '/', config }) => { export const destroyScope = ({ server, model, prefix = '/', config }) => {
const scopes = Object.keys(model.options.scopes);
server.route({ server.route({
method: 'DELETE', method: 'DELETE',
path: path.join(prefix, model._plural, '{scope}'), path: path.join(prefix, model._plural, '{scope}'),
@ -286,7 +288,13 @@ export const destroyScope = ({ server, model, prefix = '/', config }) => {
const listAsJSON = list.map((item) => item.toJSON()); const listAsJSON = list.map((item) => item.toJSON());
reply(listAsJSON.length === 1 ? listAsJSON[0] : listAsJSON); reply(listAsJSON.length === 1 ? listAsJSON[0] : listAsJSON);
}, },
config, config: _.defaultsDeep(config, {
validate: {
params: {
scope: joi.string().valid(...scopes),
},
},
}),
}); });
}; };
@ -307,7 +315,14 @@ export const update = ({ server, model, prefix = '/', config }) => {
reply(instance.toJSON()); reply(instance.toJSON());
}, },
config, config: _.defaultsDeep(config, {
validate: {
payload: joi.object().required(),
params: {
id: joi.any(),
},
},
}),
}); });
}; };

View File

@ -37,7 +37,7 @@ test.beforeEach('setup request stub', (t) => {
t.context.request = { t.context.request = {
query: {}, query: {},
payload: {}, payload: {},
models: t.context.models, models: [t.context.model],
}; };
}); });
@ -126,8 +126,6 @@ test('crud#list handler', async (t) => {
const response = reply.args[0][0]; const response = reply.args[0][0];
t.falsy(response instanceof Error, response);
t.deepEqual( t.deepEqual(
response, response,
models.map(({ id }) => ({ id })), models.map(({ id }) => ({ id })),
@ -157,75 +155,3 @@ test('crud#list handler if parseInclude errors', async (t) => {
'responds with a Boom error' 'responds with a Boom error'
); );
}); });
test('crud#list handler with limit', async (t) => {
const { server, model, request, reply, models } = t.context;
const { findAll } = model;
// set the limit
request.query.limit = 1;
list({ server, model });
const { handler } = server.route.args[0][0];
model.findAll.resolves(models);
try {
await handler(request, reply);
} catch (e) {
t.ifError(e, 'does not error while handling');
} finally {
t.pass('does not error while handling');
}
t.truthy(
reply.calledOnce
, 'calls reply only once'
);
const response = reply.args[0][0];
const findAllArgs = findAll.args[0][0];
t.falsy(response instanceof Error, response);
t.is(
findAllArgs.limit,
request.query.limit,
'queries with the limit'
);
});
test('crud#list handler with order', async (t) => {
const { server, model, request, reply, models } = t.context;
const { findAll } = model;
// set the limit
request.query.order = 'key';
list({ server, model });
const { handler } = server.route.args[0][0];
model.findAll.resolves(models);
try {
await handler(request, reply);
} catch (e) {
t.ifError(e, 'does not error while handling');
} finally {
t.pass('does not error while handling');
}
t.truthy(
reply.calledOnce
, 'calls reply only once'
);
const response = reply.args[0][0];
const findAllArgs = findAll.args[0][0];
t.falsy(response instanceof Error, response);
t.deepEqual(
findAllArgs.order,
[request.query.order],
'queries with the order as an array b/c that\'s what sequelize wants'
);
});

View File

@ -1,15 +1,6 @@
import { set, get } from 'lodash'; import { defaultsDeep } from 'lodash';
import joi from 'joi'; import joi from 'joi';
// if the custom validation is a joi object we need to concat
// else, assume it's an plain object and we can just add it in with .keys
const concatToJoiObject = (joi, candidate) => {
if (!candidate) return joi;
else if (candidate.isJoi) return joi.concat(candidate);
else return joi.keys(candidate);
};
export const sequelizeOperators = { export const sequelizeOperators = {
$and: joi.any(), $and: joi.any(),
$or: joi.any(), $or: joi.any(),
@ -56,100 +47,41 @@ export const payloadMethods = [
'update', 'update',
]; ];
export const scopeParamsMethods = [ export default ({ method, attributeValidation, associationValidation, config = {} }) => {
'destroyScope',
'scope',
];
export const idParamsMethods = [
'get',
'update',
];
export const restrictMethods = [
'list',
'scope',
];
export default ({
method, attributeValidation, associationValidation, scopes = [], config = {},
}) => {
const hasWhere = whereMethods.includes(method); const hasWhere = whereMethods.includes(method);
const hasInclude = includeMethods.includes(method); const hasInclude = includeMethods.includes(method);
const hasPayload = payloadMethods.includes(method); const hasPayload = payloadMethods.includes(method);
const hasScopeParams = scopeParamsMethods.includes(method); const methodConfig = { ...config };
const hasIdParams = idParamsMethods.includes(method);
const hasRestrictMethods = restrictMethods.includes(method);
// clone the config so we don't modify it on multiple passes.
let methodConfig = { ...config, validate: { ...config.validate } };
if (hasWhere) { if (hasWhere) {
const query = concatToJoiObject(joi.object() defaultsDeep(methodConfig, {
.keys({ validate: {
query: {
...attributeValidation, ...attributeValidation,
...sequelizeOperators, ...sequelizeOperators,
}), },
get(methodConfig, 'validate.query') },
); });
methodConfig = set(methodConfig, 'validate.query', query);
} }
if (hasInclude) { if (hasInclude) {
const query = concatToJoiObject(joi.object() defaultsDeep(methodConfig, {
.keys({ validate: {
query: {
...associationValidation, ...associationValidation,
}), },
get(methodConfig, 'validate.query') },
); });
methodConfig = set(methodConfig, 'validate.query', query);
} }
if (hasPayload) { if (hasPayload) {
const payload = concatToJoiObject(joi.object() defaultsDeep(methodConfig, {
.keys({ validate: {
payload: {
...attributeValidation, ...attributeValidation,
}), },
get(methodConfig, 'validate.payload') },
); });
methodConfig = set(methodConfig, 'validate.payload', payload);
}
if (hasScopeParams) {
const params = concatToJoiObject(joi.object()
.keys({
scope: joi.string().valid(...scopes),
}),
get(methodConfig, 'validate.params')
);
methodConfig = set(methodConfig, 'validate.params', params);
}
if (hasIdParams) {
const params = concatToJoiObject(joi.object()
.keys({
id: joi.any(),
}),
get(methodConfig, 'validate.params')
);
methodConfig = set(methodConfig, 'validate.params', params);
}
if (hasRestrictMethods) {
const query = concatToJoiObject(joi.object()
.keys({
limit: joi.number().min(0).integer(),
offset: joi.number().min(0).integer(),
order: joi.array(),
}),
get(methodConfig, 'validate.query')
);
methodConfig = set(methodConfig, 'validate.query', query);
} }
return methodConfig; return methodConfig;

View File

@ -5,23 +5,16 @@ import
whereMethods, whereMethods,
includeMethods, includeMethods,
payloadMethods, payloadMethods,
scopeParamsMethods,
idParamsMethods,
restrictMethods,
sequelizeOperators, sequelizeOperators,
} from './get-config-for-method.js'; } from './get-config-for-method.js';
test.beforeEach((t) => { test.beforeEach((t) => {
t.context.models = ['MyModel'];
t.context.scopes = ['aScope'];
t.context.attributeValidation = { t.context.attributeValidation = {
myKey: joi.any(), myKey: joi.any(),
}; };
t.context.associationValidation = { t.context.associationValidation = {
include: joi.array().items(joi.string().valid(t.context.models)), include: ['MyModel'],
}; };
t.context.config = { t.context.config = {
@ -29,10 +22,11 @@ test.beforeEach((t) => {
}; };
}); });
test('validate.query seqeulizeOperators', (t) => { test('get-config-for-method validate.query seqeulizeOperators', (t) => {
whereMethods.forEach((method) => { whereMethods.forEach((method) => {
const configForMethod = getConfigForMethod({ method }); const configForMethod = getConfigForMethod({ method });
const { query } = configForMethod.validate; const { query } = configForMethod.validate;
const configForMethodValidateQueryKeys = Object.keys(query);
t.truthy( t.truthy(
query, query,
@ -40,20 +34,15 @@ test('validate.query seqeulizeOperators', (t) => {
); );
Object.keys(sequelizeOperators).forEach((operator) => { Object.keys(sequelizeOperators).forEach((operator) => {
t.ifError( t.truthy(
query.validate({ [operator]: true }).error configForMethodValidateQueryKeys.includes(operator),
, `applies sequelize operator "${operator}" in validate.where for ${method}` `applies sequelize operator "${operator}" in validate.where for ${method}`
); );
}); });
t.truthy(
query.validate({ notAThing: true }).error
, 'errors on a non-valid key'
);
}); });
}); });
test('validate.query attributeValidation', (t) => { test('get-config-for-method validate.query attributeValidation', (t) => {
const { attributeValidation } = t.context; const { attributeValidation } = t.context;
whereMethods.forEach((method) => { whereMethods.forEach((method) => {
@ -61,96 +50,16 @@ test('validate.query attributeValidation', (t) => {
const { query } = configForMethod.validate; const { query } = configForMethod.validate;
Object.keys(attributeValidation).forEach((key) => { Object.keys(attributeValidation).forEach((key) => {
t.ifError( t.truthy(
query.validate({ [key]: true }).error query[key]
, `applies attributeValidation (${key}) to validate.query` , `applies attributeValidation (${key}) to validate.query`
); );
}); });
t.truthy(
query.validate({ notAThing: true }).error
, 'errors on a non-valid key'
);
}); });
}); });
test('query attributeValidation w/ config as plain object', (t) => { test('get-config-for-method validate.query associationValidation', (t) => {
const { attributeValidation } = t.context; const { attributeValidation, associationValidation } = t.context;
const config = {
validate: {
query: {
aKey: joi.boolean(),
},
},
};
whereMethods.forEach((method) => {
const configForMethod = getConfigForMethod({
method,
attributeValidation,
config,
});
const { query } = configForMethod.validate;
const keys = [
...Object.keys(attributeValidation),
...Object.keys(config.validate.query),
];
keys.forEach((key) => {
t.ifError(
query.validate({ [key]: true }).error
, `applies ${key} to validate.query`
);
});
t.truthy(
query.validate({ notAThing: true }).error
, 'errors on a non-valid key'
);
});
});
test('query attributeValidation w/ config as joi object', (t) => {
const { attributeValidation } = t.context;
const queryKeys = {
aKey: joi.boolean(),
};
const config = {
validate: {
query: joi.object().keys(queryKeys),
},
};
whereMethods.forEach((method) => {
const configForMethod = getConfigForMethod({
method,
attributeValidation,
config,
});
const { query } = configForMethod.validate;
const keys = [
...Object.keys(attributeValidation),
...Object.keys(queryKeys),
];
keys.forEach((key) => {
t.ifError(
query.validate({ [key]: true }).error
, `applies ${key} to validate.query`
);
});
t.truthy(
query.validate({ notAThing: true }).error
, 'errors on a non-valid key'
);
});
});
test('validate.query associationValidation', (t) => {
const { attributeValidation, associationValidation, models } = t.context;
includeMethods.forEach((method) => { includeMethods.forEach((method) => {
const configForMethod = getConfigForMethod({ const configForMethod = getConfigForMethod({
@ -161,106 +70,22 @@ test('validate.query associationValidation', (t) => {
const { query } = configForMethod.validate; const { query } = configForMethod.validate;
Object.keys(attributeValidation).forEach((key) => { Object.keys(attributeValidation).forEach((key) => {
t.ifError( t.truthy(
query.validate({ [key]: true }).error query[key]
, `applies attributeValidation (${key}) to validate.query when include should be applied` , `applies attributeValidation (${key}) to validate.query when include should be applied`
); );
}); });
Object.keys(associationValidation).forEach((key) => { Object.keys(associationValidation).forEach((key) => {
t.ifError( t.truthy(
query.validate({ [key]: models }).error query[key]
, `applies associationValidation (${key}) to validate.query when include should be applied` , `applies associationValidation (${key}) to validate.query when include should be applied`
); );
}); });
t.truthy(
query.validate({ notAThing: true }).error
, 'errors on a non-valid key'
);
}); });
}); });
test('query associationValidation w/ config as plain object', (t) => { test('get-config-for-method validate.payload associationValidation', (t) => {
const { associationValidation, models } = t.context;
const config = {
validate: {
query: {
aKey: joi.boolean(),
},
},
};
includeMethods.forEach((method) => {
const configForMethod = getConfigForMethod({
method,
associationValidation,
config,
});
const { query } = configForMethod.validate;
Object.keys(associationValidation).forEach((key) => {
t.ifError(
query.validate({ [key]: models }).error
, `applies ${key} to validate.query`
);
});
Object.keys(config.validate.query).forEach((key) => {
t.ifError(
query.validate({ [key]: true }).error
, `applies ${key} to validate.query`
);
});
t.truthy(
query.validate({ notAThing: true }).error
, 'errors on a non-valid key'
);
});
});
test('query associationValidation w/ config as joi object', (t) => {
const { associationValidation, models } = t.context;
const queryKeys = {
aKey: joi.boolean(),
};
const config = {
validate: {
query: joi.object().keys(queryKeys),
},
};
includeMethods.forEach((method) => {
const configForMethod = getConfigForMethod({
method,
associationValidation,
config,
});
const { query } = configForMethod.validate;
Object.keys(associationValidation).forEach((key) => {
t.ifError(
query.validate({ [key]: models }).error
, `applies ${key} to validate.query`
);
});
Object.keys(queryKeys).forEach((key) => {
t.ifError(
query.validate({ [key]: true }).error
, `applies ${key} to validate.query`
);
});
t.truthy(
query.validate({ notAThing: true }).error
, 'errors on a non-valid key'
);
});
});
test('validate.payload associationValidation', (t) => {
const { attributeValidation } = t.context; const { attributeValidation } = t.context;
payloadMethods.forEach((method) => { payloadMethods.forEach((method) => {
@ -268,308 +93,20 @@ test('validate.payload associationValidation', (t) => {
const { payload } = configForMethod.validate; const { payload } = configForMethod.validate;
Object.keys(attributeValidation).forEach((key) => { Object.keys(attributeValidation).forEach((key) => {
t.ifError( t.truthy(
payload.validate({ [key]: true }).error payload[key]
, `applies attributeValidation (${key}) to validate.payload` , `applies attributeValidation (${key}) to validate.payload`
); );
}); });
t.truthy(
payload.validate({ notAThing: true }).error
, 'errors on a non-valid key'
);
}); });
}); });
test('payload attributeValidation w/ config as plain object', (t) => { test('get-config-for-method does not modify initial config on multiple passes', (t) => {
const { attributeValidation } = t.context;
const config = {
validate: {
payload: {
aKey: joi.boolean(),
},
},
};
payloadMethods.forEach((method) => {
const configForMethod = getConfigForMethod({
method,
attributeValidation,
config,
});
const { payload } = configForMethod.validate;
const keys = [
...Object.keys(attributeValidation),
...Object.keys(config.validate.payload),
];
keys.forEach((key) => {
t.ifError(
payload.validate({ [key]: true }).error
, `applies ${key} to validate.payload`
);
});
t.truthy(
payload.validate({ notAThing: true }).error
, 'errors on a non-valid key'
);
});
});
test('payload attributeValidation w/ config as joi object', (t) => {
const { attributeValidation } = t.context;
const payloadKeys = {
aKey: joi.boolean(),
};
const config = {
validate: {
payload: joi.object().keys(payloadKeys),
},
};
payloadMethods.forEach((method) => {
const configForMethod = getConfigForMethod({
method,
attributeValidation,
config,
});
const { payload } = configForMethod.validate;
const keys = [
...Object.keys(attributeValidation),
...Object.keys(payloadKeys),
];
keys.forEach((key) => {
t.ifError(
payload.validate({ [key]: true }).error
, `applies ${key} to validate.payload`
);
});
t.truthy(
payload.validate({ notAThing: true }).error
, 'errors on a non-valid key'
);
});
});
test('validate.params scopeParamsMethods', (t) => {
const { scopes } = t.context;
scopeParamsMethods.forEach((method) => {
const configForMethod = getConfigForMethod({ method, scopes });
const { params } = configForMethod.validate;
scopes.forEach((key) => {
t.ifError(
params.validate({ scope: key }).error
, `applies "scope: ${key}" to validate.params`
);
});
t.truthy(
params.validate({ scope: 'notAthing' }).error
, 'errors on a non-valid key'
);
});
});
test('params scopeParamsMethods w/ config as plain object', (t) => {
const { scopes } = t.context;
const config = {
validate: {
params: {
aKey: joi.boolean(),
},
},
};
scopeParamsMethods.forEach((method) => {
const configForMethod = getConfigForMethod({
method,
scopes,
config,
});
const { params } = configForMethod.validate;
scopes.forEach((key) => {
t.ifError(
params.validate({ scope: key }).error
, `applies "scope: ${key}" to validate.params`
);
});
Object.keys(config.validate.params).forEach((key) => {
t.ifError(
params.validate({ [key]: true }).error
, `applies ${key} to validate.params`
);
});
t.truthy(
params.validate({ notAThing: true }).error
, 'errors on a non-valid key'
);
});
});
test('params scopeParamsMethods w/ config as joi object', (t) => {
const { scopes } = t.context;
const paramsKeys = {
aKey: joi.boolean(),
};
const config = {
validate: {
params: joi.object().keys(paramsKeys),
},
};
scopeParamsMethods.forEach((method) => {
const configForMethod = getConfigForMethod({
method,
scopes,
config,
});
const { params } = configForMethod.validate;
scopes.forEach((key) => {
t.ifError(
params.validate({ scope: key }).error
, `applies "scope: ${key}" to validate.params`
);
});
Object.keys(paramsKeys).forEach((key) => {
t.ifError(
params.validate({ [key]: true }).error
, `applies ${key} to validate.params`
);
});
t.truthy(
params.validate({ notAThing: true }).error
, 'errors on a non-valid key'
);
});
});
test('validate.payload idParamsMethods', (t) => {
idParamsMethods.forEach((method) => {
const configForMethod = getConfigForMethod({ method });
const { params } = configForMethod.validate;
t.ifError(
params.validate({ id: 'aThing' }).error
, 'applies id to validate.params'
);
});
});
test('validate.query restrictMethods', (t) => {
restrictMethods.forEach((method) => {
const configForMethod = getConfigForMethod({ method });
const { query } = configForMethod.validate;
const restrictKeys = ['limit', 'offset'];
restrictKeys.forEach((key) => {
t.ifError(
query.validate({ [key]: 0 }).error
, `applies restriction (${key}) to validate.query`
);
});
t.ifError(
query.validate({ order: ['thing', 'DESC'] }).error
, 'applies `order` to validate.query'
);
t.truthy(
query.validate({ notAThing: true }).error
, 'errors on a non-valid key'
);
});
});
test('validate.query restrictMethods w/ config as plain object', (t) => {
const config = {
validate: {
query: {
aKey: joi.boolean(),
},
},
};
restrictMethods.forEach((method) => {
const configForMethod = getConfigForMethod({
method,
config,
});
const { query } = configForMethod.validate;
const keys = [
...Object.keys(config.validate.query),
];
keys.forEach((key) => {
t.ifError(
query.validate({ [key]: true }).error
, `applies ${key} to validate.query`
);
});
t.truthy(
query.validate({ notAThing: true }).error
, 'errors on a non-valid key'
);
});
});
test('validate.query restrictMethods w/ config as joi object', (t) => {
const queryKeys = {
aKey: joi.boolean(),
};
const config = {
validate: {
query: joi.object().keys(queryKeys),
},
};
whereMethods.forEach((method) => {
const configForMethod = getConfigForMethod({
method,
config,
});
const { query } = configForMethod.validate;
const keys = [
...Object.keys(queryKeys),
];
keys.forEach((key) => {
t.ifError(
query.validate({ [key]: true }).error
, `applies ${key} to validate.query`
);
});
t.truthy(
query.validate({ notAThing: true }).error
, 'errors on a non-valid key'
);
});
});
test('does not modify initial config on multiple passes', (t) => {
const { config } = t.context; const { config } = t.context;
const originalConfig = { ...config }; const originalConfig = { ...config };
whereMethods.forEach((method) => { whereMethods.forEach((method) => {
getConfigForMethod({ method, ...t.context }); getConfigForMethod({ method, config });
}); });
t.deepEqual( t.deepEqual(

View File

@ -1,13 +1,9 @@
import { omit, identity, toNumber, isString, isUndefined } from 'lodash'; import { omit, identity } from 'lodash';
import { notImplemented } from 'boom'; import { notImplemented } from 'boom';
const sequelizeKeys = ['include', 'order', 'limit', 'offset'];
export const parseInclude = request => { export const parseInclude = request => {
const include = Array.isArray(request.query.include) const include = Array.isArray(request.query.include) ? request.query.include
? request.query.include : [request.query.include];
: [request.query.include]
;
const noGetDb = typeof request.getDb !== 'function'; const noGetDb = typeof request.getDb !== 'function';
const noRequestModels = !request.models; const noRequestModels = !request.models;
@ -31,7 +27,7 @@ export const parseInclude = request => {
}; };
export const parseWhere = request => { export const parseWhere = request => {
const where = omit(request.query, sequelizeKeys); const where = omit(request.query, 'include');
for (const key of Object.keys(where)) { for (const key of Object.keys(where)) {
try { try {
@ -44,38 +40,6 @@ export const parseWhere = request => {
return where; return where;
}; };
export const parseLimitAndOffset = (request) => {
const { limit, offset } = request.query;
const out = {};
if (!isUndefined(limit)) {
out.limit = toNumber(limit);
}
if (!isUndefined(offset)) {
out.offset = toNumber(offset);
}
return out;
};
export const parseOrder = (request) => {
const { order } = request.query;
if (!order) return null;
// transform to an array so sequelize will escape the input for us and
// maintain security. See http://docs.sequelizejs.com/en/latest/docs/querying/#ordering
if (isString(order)) return order.split(' ');
for (const key of Object.keys(order)) {
try {
order[key] = JSON.parse(order[key]);
} catch (e) {
//
}
}
return order;
};
export const getMethod = (model, association, plural = true, method = 'get') => { export const getMethod = (model, association, plural = true, method = 'get') => {
const a = plural ? association.original.plural : association.original.singular; const a = plural ? association.original.plural : association.original.singular;
const b = plural ? association.original.singular : association.original.plural; // alternative const b = plural ? association.original.singular : association.original.plural; // alternative

View File

@ -1,113 +0,0 @@
import test from 'ava';
import { parseLimitAndOffset, parseOrder, parseWhere } from './utils.js';
test.beforeEach((t) => {
t.context.request = { query: {} };
});
test('parseLimitAndOffset is a function', (t) => {
t.is(typeof parseLimitAndOffset, 'function');
});
test('parseLimitAndOffset returns limit and offset', (t) => {
const { request } = t.context;
request.query.limit = 1;
request.query.offset = 2;
request.query.thing = 'hi';
t.is(
parseLimitAndOffset(request).limit
, request.query.limit
);
t.is(
parseLimitAndOffset(request).offset
, request.query.offset
);
});
test('parseLimitAndOffset returns limit and offset as numbers', (t) => {
const { request } = t.context;
const limit = 1;
const offset = 2;
request.query.limit = `${limit}`;
request.query.offset = `${offset}`;
request.query.thing = 'hi';
t.is(
parseLimitAndOffset(request).limit
, limit
);
t.is(
parseLimitAndOffset(request).offset
, offset
);
});
test('parseOrder is a function', (t) => {
t.is(typeof parseOrder, 'function');
});
test('parseOrder returns order when a string', (t) => {
const { request } = t.context;
const order = 'thing';
request.query.order = order;
request.query.thing = 'hi';
t.deepEqual(
parseOrder(request)
, [order]
);
});
test('parseOrder returns order when json', (t) => {
const { request } = t.context;
const order = [{ model: 'User' }, 'DESC'];
request.query.order = [JSON.stringify({ model: 'User' }), 'DESC'];
request.query.thing = 'hi';
t.deepEqual(
parseOrder(request)
, order
);
});
test('parseOrder returns null when not defined', (t) => {
const { request } = t.context;
request.query.thing = 'hi';
t.is(
parseOrder(request)
, null
);
});
test('parseWhere is a function', (t) => {
t.is(typeof parseWhere, 'function');
});
test('parseWhere returns the non-sequelize keys', (t) => {
const { request } = t.context;
request.query.order = 'thing';
request.query.include = 'User';
request.query.limit = 2;
request.query.thing = 'hi';
t.deepEqual(
parseWhere(request)
, { thing: 'hi' }
);
});
test('parseWhere returns json converted keys', (t) => {
const { request } = t.context;
request.query.order = 'hi';
request.query.thing = '{"id": {"$in": [2, 3]}}';
t.deepEqual(
parseWhere(request)
, { thing: { id: { $in: [2, 3] } } }
);
});