Skip to content

Commit

Permalink
fix: allow save of collection with an undefined point
Browse files Browse the repository at this point in the history
  • Loading branch information
DanRibbens committed Aug 25, 2021
1 parent 30f1750 commit f80646c
Show file tree
Hide file tree
Showing 11 changed files with 60 additions and 32 deletions.
21 changes: 17 additions & 4 deletions demo/collections/Geolocation.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
/* eslint-disable no-param-reassign */
import { CollectionConfig } from '../../src/collections/config/types';

const validateFieldTransformAction = (hook: string, value = null) => {
if (value !== null && !Array.isArray(value)) {
console.error(hook, value);
throw new Error('Field transformAction should convert value to array [x, y] and not { coordinates: [x, y] }');
}
return value;
};

const Geolocation: CollectionConfig = {
slug: 'geolocation',
labels: {
Expand All @@ -24,23 +32,22 @@ const Geolocation: CollectionConfig = {
afterRead: [
(operation) => {
const { doc } = operation;
// console.log(doc);
doc.afterReadHook = !doc.location?.coordinates;
return doc;
},
],
afterChange: [
(operation) => {
const { doc } = operation;
operation.doc.afterChangeHook = !doc.location?.coordinates;
return operation.doc;
doc.afterChangeHook = !doc.location?.coordinates;
return doc;
},
],
afterDelete: [
(operation) => {
const { doc } = operation;
operation.doc.afterDeleteHook = !doc.location?.coordinates;
return operation.doc;
return doc;
},
],
},
Expand All @@ -49,6 +56,12 @@ const Geolocation: CollectionConfig = {
name: 'location',
type: 'point',
label: 'Location',
hooks: {
beforeValidate: [({ value }) => validateFieldTransformAction('beforeValidate', value)],
beforeChange: [({ value }) => validateFieldTransformAction('beforeChange', value)],
afterChange: [({ value }) => validateFieldTransformAction('afterChange', value)],
afterRead: [({ value }) => validateFieldTransformAction('afterRead', value)],
},
},
{
name: 'localizedPoint',
Expand Down
14 changes: 14 additions & 0 deletions demo/collections/Localized.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { CollectionConfig } from '../../src/collections/config/types';
import { Block } from '../../src/fields/config/types';

const validateLocalizationTransform = (hook: string, value = null) => {
if (value !== null && typeof value !== 'string') {
console.error(hook, value);
throw new Error('Field text transformation in hook is wonky');
}
return value;
};

const RichTextBlock: Block = {
slug: 'richTextBlock',
labels: {
Expand Down Expand Up @@ -46,6 +54,12 @@ const LocalizedPosts: CollectionConfig = {
required: true,
unique: true,
localized: true,
hooks: {
beforeValidate: [({ value }) => validateLocalizationTransform('beforeValidate', value)],
beforeChange: [({ value }) => validateLocalizationTransform('beforeChange', value)],
afterChange: [({ value }) => validateLocalizationTransform('afterChange', value)],
afterRead: [({ value }) => validateLocalizationTransform('afterRead', value)],
},
},
{
name: 'summary',
Expand Down
5 changes: 2 additions & 3 deletions src/collections/bindCollection.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { NextFunction, Response } from 'express';
import { PayloadRequest } from '../express/types';
import { NextFunction, Request, Response } from 'express';

const bindCollectionMiddleware = (collection: string) => (req: PayloadRequest, res: Response, next: NextFunction) => {
const bindCollectionMiddleware = (collection: string) => (req: Request & { collection: string }, res: Response, next: NextFunction) => {
req.collection = collection;
next();
};
Expand Down
2 changes: 1 addition & 1 deletion src/collections/buildSchema.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import paginate from 'mongoose-paginate-v2';
import { Schema } from 'mongoose';
import { SanitizedConfig } from '../../config';
import { SanitizedConfig } from '../config/types';
import buildQueryPlugin from '../mongoose/buildQuery';
import buildSchema from '../mongoose/buildSchema';
import { SanitizedCollectionConfig } from './config/types';
Expand Down
2 changes: 1 addition & 1 deletion src/collections/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import apiKeyStrategy from '../auth/strategies/apiKey';
import buildSchema from './buildSchema';
import bindCollectionMiddleware from './bindCollection';
import { SanitizedCollectionConfig } from './config/types';
import { SanitizedConfig } from '../../config';
import { SanitizedConfig } from '../config/types';
import { Payload } from '../index';

const LocalStrategy = Passport.Strategy;
Expand Down
1 change: 0 additions & 1 deletion src/collections/tests/pointField.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ describe('GeoJSON', () => {
let doc;

beforeAll(async (done) => {
// create document a
const create = await fetch(`${serverURL}/api/geolocation`, {
body: JSON.stringify({ location, localizedPoint }),
headers,
Expand Down
2 changes: 1 addition & 1 deletion src/express/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export type PayloadRequest = Request & {
payload: Payload;
locale?: string;
fallbackLocale?: string;
collection?: Collection | string;
collection?: Collection;
payloadAPI: 'REST' | 'local' | 'graphQL'
file?: UploadedFile
user: User | null
Expand Down
4 changes: 2 additions & 2 deletions src/fields/hookPromise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ type Arguments = {
fullData: Record<string, unknown>
}

const hookPromise = async ({
const hookPromise = ({
data,
field,
hook,
req,
operation,
fullOriginalDoc,
fullData,
}: Arguments): Promise<void> => {
}: Arguments) => async (): Promise<void> => {
const resultingData = data;

if (field.hooks && field.hooks[hook]) {
Expand Down
21 changes: 12 additions & 9 deletions src/fields/performFieldOperations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,18 @@ export default async function performFieldOperations(this: Payload, entityConfig
docWithLocales,
});

if (hook === 'beforeChange') {
transformActions.forEach((action) => action());
}

unflattenLocaleActions.forEach((action) => action());

if (hook === 'afterRead') {
transformActions.forEach((action) => action());
}

hookPromises.forEach((promise) => promise());

await Promise.all(hookPromises);

validationPromises.forEach((promise) => promise());
Expand All @@ -113,15 +125,6 @@ export default async function performFieldOperations(this: Payload, entityConfig
throw new ValidationError(errors);
}

if (hook === 'beforeChange') {
transformActions.forEach((action) => action());
}

unflattenLocaleActions.forEach((action) => action());

if (hook === 'afterRead') {
transformActions.forEach((action) => action());
}

await Promise.all(accessPromises);

Expand Down
18 changes: 10 additions & 8 deletions src/fields/traverseFields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type Arguments = {
depth: number
currentDepth: number
hook: HookName
hookPromises: Promise<void>[]
hookPromises: (() => Promise<void>)[]
fullOriginalDoc: Record<string, any>
fullData: Record<string, any>
validationPromises: (() => Promise<string | boolean>)[]
Expand Down Expand Up @@ -269,13 +269,15 @@ const traverseFields = (args: Arguments): void => {

if (field.type === 'point' && data[field.name]) {
transformActions.push(() => {
data[field.name] = {
type: 'Point',
coordinates: [
parseFloat(data[field.name][0]),
parseFloat(data[field.name][1]),
],
};
if (Array.isArray(data[field.name]) && data[field.name][0] !== null && data[field.name][1] !== null) {
data[field.name] = {
type: 'Point',
coordinates: [
parseFloat(data[field.name][0]),
parseFloat(data[field.name][1]),
],
};
}
});
}

Expand Down
2 changes: 0 additions & 2 deletions src/mongoose/buildSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,9 +213,7 @@ const fieldToSchemaMap = {
const baseSchema = {
type: {
type: String,
default: 'Point',
enum: ['Point'],
required: true,
},
coordinates: {
type: [Number],
Expand Down

0 comments on commit f80646c

Please sign in to comment.