Skip to content

Commit

Permalink
validate all geometry collection by type
Browse files Browse the repository at this point in the history
  • Loading branch information
ambrazasp committed Aug 23, 2023
1 parent a234ae3 commit a0c7585
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
20 changes: 20 additions & 0 deletions docs/validation/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,4 @@ export function getFeatures(geom: AllTypes): Feature[] {

export function getFeatureCollection(geom: AllTypes): FeatureCollection {
return getFeatureCollectionWithFeatures(getFeatures(geom));
}
}
29 changes: 29 additions & 0 deletions src/validate.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { isNumber, isObject } from 'lodash';
import {
AllTypes,
CoordinatesTypes,
Feature,
FeatureCollection,
Expand All @@ -9,6 +10,7 @@ import {
ValidationError,
ValidationResult,
} from './types';
import { getGeometries } from './helpers';

function transformResponse(
error?: string,
Expand Down Expand Up @@ -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();
}

0 comments on commit a0c7585

Please sign in to comment.