Created
June 10, 2017 19:36
-
-
Save anghelalexandra/249b948b5e733181ef0c42823b449c45 to your computer and use it in GitHub Desktop.
wp-pwa-sample-validate-categories
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('appticles.validation') | |
.factory('AppticlesValidation', AppticlesValidation); | |
/** | |
* @ngdoc service | |
* @name appticles.validation.AppticlesValidation | |
* | |
* @description Service for validating data coming from the API. | |
*/ | |
function AppticlesValidation() { | |
let service = { | |
validateCategories: validateCategories, | |
... | |
}; | |
return service; | |
/** | |
* @ngdoc function | |
* @name appticles.validation.AppticlesValidation#validateCategories | |
* @methodOf appticles.validation.AppticlesValidation | |
* @description Validate categories data | |
* | |
* @return {Array} An array of category objects | |
* | |
* {@link https://developer.wordpress.org/rest-api/reference/categories/#list-categorys} | |
*/ | |
function validateCategories(input) { | |
if(angular.isObject(input) && !angular.isArray(input)) { | |
if (angular.isDefined(input.data)) { | |
if (input.data.length === 0) { | |
return []; | |
} | |
let validatedCategories = input.data.map(_checkOneCategories); | |
if (validatedCategories.indexOf(false) === -1) { | |
return validatedCategories; | |
} | |
} | |
} | |
return { 'error': 'Invalid data' }; | |
} | |
/** | |
* @ngdoc function | |
* @name appticles.validation.AppticlesValidation#checkOneCategories | |
* @methodOf appticles.validation.AppticlesValidation | |
* @description Validate a single category object. | |
* | |
* @return {Boolean|Object} Return the category if it's valid, false otherwise. | |
* | |
* {@link https://developer.wordpress.org/rest-api/reference/categories/#schema} | |
*/ | |
function _checkOneCategories(category) { | |
if (angular.isDefined(category.id) && /^[a-z0-9]+$/i.test(category.id) && | |
angular.isDefined(category.name) && angular.isString(category.name) && | |
angular.isDefined(category.slug) && angular.isString(category.slug) && | |
angular.isDefined(category.link) && angular.isString(category.link) && | |
(angular.isUndefined(category.parent) || /^[a-z0-9]+$/i.test(category.parent) )) { | |
return { | |
id: category.id, | |
name: category.name, | |
slug: category.slug, | |
link: category.link, | |
parent: category.parent | |
}; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment