diff --git a/docs/validation/readme.md b/docs/validation/readme.md index c842138..9ef7f5a 100644 --- a/docs/validation/readme.md +++ b/docs/validation/readme.md @@ -7,6 +7,7 @@ | `validateFeature` | `feature: Feature` | [More info](#validatefeature) | | `validateFeatures` | `features: Feature[]` | [More info](#validatefeatures) | | `validateFeatureCollection` | `collection: FeatureCollection` | [More info](#validatefeaturecollection) | +| `validateGeometryTypes` | `types: string \| string [], geom: AllTypes` | [More info](#validategeometrytypes) | Each validation returns [ValidationResult](#validationresult) response @@ -79,6 +80,25 @@ const valid = validateFeatureCollection({ }); ``` +## validateGeometryTypes + +Example: + +```js +const valid = validateGeometryTypes(['Point'], { + type: 'FeatureCollection', + features: [ + { + type: 'Feature', + geometry: { + type: 'Point', + coordinates: [11, 22], + }, + }, + ], +}); +``` + ## ValidationResult Type, that consists of: diff --git a/src/helpers.ts b/src/helpers.ts index a33cf14..adef039 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -90,4 +90,4 @@ export function getFeatures(geom: AllTypes): Feature[] { export function getFeatureCollection(geom: AllTypes): FeatureCollection { return getFeatureCollectionWithFeatures(getFeatures(geom)); -} +} \ No newline at end of file diff --git a/src/validate.ts b/src/validate.ts index cac8a2a..08f8104 100644 --- a/src/validate.ts +++ b/src/validate.ts @@ -1,5 +1,6 @@ import { isNumber, isObject } from 'lodash'; import { + AllTypes, CoordinatesTypes, Feature, FeatureCollection, @@ -9,6 +10,7 @@ import { ValidationError, ValidationResult, } from './types'; +import { getGeometries } from './helpers'; function transformResponse( error?: string, @@ -133,3 +135,30 @@ export function validateFeatureCollection( return validateFeatures(geom.features); } + +export function validateGeometryTypes( + types: string | string[], + geom: AllTypes +) { + if (!Array.isArray(types)) types = [types]; + + const everyTypeValid = types.every((t) => + Object.values(GeometryType).includes(t) + ); + + if (!everyTypeValid) { + throw new Error(`Passed types are not valid - ["${types.join("', '")}"]`); + } + + const invalidTypes = getGeometries(geom) + .map((item) => item.type) + .filter((t) => !types.includes(t)); + + if (!invalidTypes?.length) { + return transformResponse(ValidationError.INVALID_TYPE, { + types: invalidTypes, + }); + } + + return transformResponse(); +}