| 1 | 'use strict';
|
|---|
| 2 |
|
|---|
| 3 | var SCALAR_TYPES = ['number', 'integer', 'string', 'boolean', 'null'];
|
|---|
| 4 |
|
|---|
| 5 | module.exports = function defFunc(ajv) {
|
|---|
| 6 | defFunc.definition = {
|
|---|
| 7 | type: 'array',
|
|---|
| 8 | compile: function(keys, parentSchema, it) {
|
|---|
| 9 | var equal = it.util.equal;
|
|---|
| 10 | var scalar = getScalarKeys(keys, parentSchema);
|
|---|
| 11 |
|
|---|
| 12 | return function(data) {
|
|---|
| 13 | if (data.length > 1) {
|
|---|
| 14 | for (var k=0; k < keys.length; k++) {
|
|---|
| 15 | var i, key = keys[k];
|
|---|
| 16 | if (scalar[k]) {
|
|---|
| 17 | var hash = {};
|
|---|
| 18 | for (i = data.length; i--;) {
|
|---|
| 19 | if (!data[i] || typeof data[i] != 'object') continue;
|
|---|
| 20 | var prop = data[i][key];
|
|---|
| 21 | if (prop && typeof prop == 'object') continue;
|
|---|
| 22 | if (typeof prop == 'string') prop = '"' + prop;
|
|---|
| 23 | if (hash[prop]) return false;
|
|---|
| 24 | hash[prop] = true;
|
|---|
| 25 | }
|
|---|
| 26 | } else {
|
|---|
| 27 | for (i = data.length; i--;) {
|
|---|
| 28 | if (!data[i] || typeof data[i] != 'object') continue;
|
|---|
| 29 | for (var j = i; j--;) {
|
|---|
| 30 | if (data[j] && typeof data[j] == 'object' && equal(data[i][key], data[j][key]))
|
|---|
| 31 | return false;
|
|---|
| 32 | }
|
|---|
| 33 | }
|
|---|
| 34 | }
|
|---|
| 35 | }
|
|---|
| 36 | }
|
|---|
| 37 | return true;
|
|---|
| 38 | };
|
|---|
| 39 | },
|
|---|
| 40 | metaSchema: {
|
|---|
| 41 | type: 'array',
|
|---|
| 42 | items: {type: 'string'}
|
|---|
| 43 | }
|
|---|
| 44 | };
|
|---|
| 45 |
|
|---|
| 46 | ajv.addKeyword('uniqueItemProperties', defFunc.definition);
|
|---|
| 47 | return ajv;
|
|---|
| 48 | };
|
|---|
| 49 |
|
|---|
| 50 |
|
|---|
| 51 | function getScalarKeys(keys, schema) {
|
|---|
| 52 | return keys.map(function(key) {
|
|---|
| 53 | var properties = schema.items && schema.items.properties;
|
|---|
| 54 | var propType = properties && properties[key] && properties[key].type;
|
|---|
| 55 | return Array.isArray(propType)
|
|---|
| 56 | ? propType.indexOf('object') < 0 && propType.indexOf('array') < 0
|
|---|
| 57 | : SCALAR_TYPES.indexOf(propType) >= 0;
|
|---|
| 58 | });
|
|---|
| 59 | }
|
|---|