mirror of
https://github.com/directus/directus.git
synced 2026-04-25 03:00:53 -04:00
* Typecheck across packages that are built with esbuild * Boilerplate new Errors package * No need, tsup checks with --dts * Switch to tsup * Setup dev script * Add readme * More boilerplaty things * Finish createError function * Install @directus/random * Downgrade node types * Add utility function to check if an error is a DirectusError * Use new is-error check * Install errors package * Add failed validation common error * Export common errors * Move joi convertion to utils * Export failed validation * Use new failed validation error in validate-batch * Enhance typing output of createError * Remove outdir (handled by tsup now) * Replace Exception with Error * Replace exception in test * Remove exceptions from app * Remove exceptions from app * Remove failed validation exception from users service * Remove old failed validation exception from shared * Remove exceptions package in favor of errors * Uninstall exceptions * Replace baseexception check * Migrate content too large error * Critical detail * Replace ForbiddenException * WIP remove exceptions * Add ForbiddenError to errors * HitRateLimitError * Move validation related error/helper to new validation package * Add index * Add docs * Install random * Convert TokenExpired * Convert user-suspended * Convert invalid-credentials * Move UnsupportedMediaType * Replace wrong imports for forbidden * Convert invalid-ip * Move invalid provider * Move InvalidOtp * Convert InvalidToken * Move MethodNotAllowed * Convert range not satisfiable * Move unexpect response * Move UnprocessableContent * Move IllegalAssetTransformation * Move RouteNotFound * Finalize not found * Various db errors * Move value too long * Move not null * Move record-not-unique * Move value out of range * Finish db errors * Service unavailable * GQL errors * Update packages/validation/src/errors/failed-validation.ts Co-authored-by: Azri Kahar <42867097+azrikahar@users.noreply.github.com> * Update packages/validation/src/errors/failed-validation.ts Co-authored-by: Azri Kahar <42867097+azrikahar@users.noreply.github.com> * InvalidQuery * Add test for invalid query message constructor * Invalid Payload * Finalize exceptions move * Improve type of isDirectusError * Various fixes * Fix build in api * Update websocket exceptions use * Allow optional reason for invalid config * Update errors usage in utils * Remove unused package from errors * Update lockfile * Update api/src/auth/drivers/ldap.ts Co-authored-by: Azri Kahar <42867097+azrikahar@users.noreply.github.com> * Update packages/validation/src/utils/joi-to-error-extensions.ts Co-authored-by: Azri Kahar <42867097+azrikahar@users.noreply.github.com> * Put error codes in shared enum * Replace instanceof checks in api * Fix tests I think * Tweak override names * Fix linter warnings * Set snapshots * Start fixing BB tests * Fix blackbox tests * Add changeset * Update changeset * Update extension docs to use new createError abstraction * 🙄 * Fix graphql validation error name * 🥳 * use ErrorCode.Forbidden * fix blackbox auth login test * Add license files * Rename preMutationException to preMutationError * Remove unused ms dep & sort package.json * Remove periods from error messages for consistency Co-authored-by: Azri Kahar <42867097+azrikahar@users.noreply.github.com> * Add optional code check * Use updated error code checker * Rename InvalidConfigError to InvalidProviderConfigError --------- Co-authored-by: Azri Kahar <42867097+azrikahar@users.noreply.github.com> Co-authored-by: Pascal Jufer <pascal-jufer@bluewin.ch> Co-authored-by: ian <licitdev@gmail.com>
158 lines
5.3 KiB
TypeScript
158 lines
5.3 KiB
TypeScript
import Joi from 'joi';
|
|
import { InvalidPayloadError } from '../errors/index.js';
|
|
import type { SnapshotDiffWithHash, SnapshotWithHash } from '../types/snapshot.js';
|
|
import { DiffKind } from '../types/snapshot.js';
|
|
|
|
const deepDiffSchema = Joi.object({
|
|
kind: Joi.string()
|
|
.valid(...Object.values(DiffKind))
|
|
.required(),
|
|
path: Joi.array().items(Joi.alternatives().try(Joi.string(), Joi.number())),
|
|
lhs: Joi.any().when('kind', { is: [DiffKind.NEW, DiffKind.ARRAY], then: Joi.optional(), otherwise: Joi.required() }),
|
|
rhs: Joi.any().when('kind', {
|
|
is: [DiffKind.DELETE, DiffKind.ARRAY],
|
|
then: Joi.optional(),
|
|
otherwise: Joi.required(),
|
|
}),
|
|
index: Joi.number().when('kind', { is: DiffKind.ARRAY, then: Joi.required() }),
|
|
item: Joi.link('#deepdiff').when('kind', { is: DiffKind.ARRAY, then: Joi.required() }),
|
|
}).id('deepdiff');
|
|
|
|
const applyJoiSchema = Joi.object({
|
|
hash: Joi.string().required(),
|
|
diff: Joi.object({
|
|
collections: Joi.array()
|
|
.items(
|
|
Joi.object({
|
|
collection: Joi.string().required(),
|
|
diff: Joi.array().items(deepDiffSchema).required(),
|
|
})
|
|
)
|
|
.required(),
|
|
fields: Joi.array()
|
|
.items(
|
|
Joi.object({
|
|
collection: Joi.string().required(),
|
|
field: Joi.string().required(),
|
|
diff: Joi.array().items(deepDiffSchema).required(),
|
|
})
|
|
)
|
|
.required(),
|
|
relations: Joi.array()
|
|
.items(
|
|
Joi.object({
|
|
collection: Joi.string().required(),
|
|
field: Joi.string().required(),
|
|
related_collection: Joi.string().allow(null),
|
|
diff: Joi.array().items(deepDiffSchema).required(),
|
|
})
|
|
)
|
|
.required(),
|
|
}).required(),
|
|
});
|
|
|
|
/**
|
|
* Validates the diff against the current schema snapshot.
|
|
*
|
|
* @returns True if the diff can be applied (valid & not empty).
|
|
*/
|
|
export function validateApplyDiff(applyDiff: SnapshotDiffWithHash, currentSnapshotWithHash: SnapshotWithHash) {
|
|
const { error } = applyJoiSchema.validate(applyDiff);
|
|
if (error) throw new InvalidPayloadError({ reason: error.message });
|
|
|
|
// No changes to apply
|
|
if (
|
|
applyDiff.diff.collections.length === 0 &&
|
|
applyDiff.diff.fields.length === 0 &&
|
|
applyDiff.diff.relations.length === 0
|
|
) {
|
|
return false;
|
|
}
|
|
|
|
// Diff can be applied due to matching hash
|
|
if (applyDiff.hash === currentSnapshotWithHash.hash) return true;
|
|
|
|
for (const diffCollection of applyDiff.diff.collections) {
|
|
const collection = diffCollection.collection;
|
|
|
|
if (diffCollection.diff[0]?.kind === DiffKind.NEW) {
|
|
const existingCollection = currentSnapshotWithHash.collections.find(
|
|
(c) => c.collection === diffCollection.collection
|
|
);
|
|
|
|
if (existingCollection) {
|
|
throw new InvalidPayloadError({
|
|
reason: `Provided diff is trying to create collection "${collection}" but it already exists. Please generate a new diff and try again`,
|
|
});
|
|
}
|
|
} else if (diffCollection.diff[0]?.kind === DiffKind.DELETE) {
|
|
const existingCollection = currentSnapshotWithHash.collections.find(
|
|
(c) => c.collection === diffCollection.collection
|
|
);
|
|
|
|
if (!existingCollection) {
|
|
throw new InvalidPayloadError({
|
|
reason: `Provided diff is trying to delete collection "${collection}" but it does not exist. Please generate a new diff and try again`,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
for (const diffField of applyDiff.diff.fields) {
|
|
const field = `${diffField.collection}.${diffField.field}`;
|
|
|
|
if (diffField.diff[0]?.kind === DiffKind.NEW) {
|
|
const existingField = currentSnapshotWithHash.fields.find(
|
|
(f) => f.collection === diffField.collection && f.field === diffField.field
|
|
);
|
|
|
|
if (existingField) {
|
|
throw new InvalidPayloadError({
|
|
reason: `Provided diff is trying to create field "${field}" but it already exists. Please generate a new diff and try again`,
|
|
});
|
|
}
|
|
} else if (diffField.diff[0]?.kind === DiffKind.DELETE) {
|
|
const existingField = currentSnapshotWithHash.fields.find(
|
|
(f) => f.collection === diffField.collection && f.field === diffField.field
|
|
);
|
|
|
|
if (!existingField) {
|
|
throw new InvalidPayloadError({
|
|
reason: `Provided diff is trying to delete field "${field}" but it does not exist. Please generate a new diff and try again`,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
for (const diffRelation of applyDiff.diff.relations) {
|
|
let relation = `${diffRelation.collection}.${diffRelation.field}`;
|
|
if (diffRelation.related_collection) relation += `-> ${diffRelation.related_collection}`;
|
|
|
|
if (diffRelation.diff[0]?.kind === DiffKind.NEW) {
|
|
const existingRelation = currentSnapshotWithHash.relations.find(
|
|
(r) => r.collection === diffRelation.collection && r.field === diffRelation.field
|
|
);
|
|
|
|
if (existingRelation) {
|
|
throw new InvalidPayloadError({
|
|
reason: `Provided diff is trying to create relation "${relation}" but it already exists. Please generate a new diff and try again`,
|
|
});
|
|
}
|
|
} else if (diffRelation.diff[0]?.kind === DiffKind.DELETE) {
|
|
const existingRelation = currentSnapshotWithHash.relations.find(
|
|
(r) => r.collection === diffRelation.collection && r.field === diffRelation.field
|
|
);
|
|
|
|
if (!existingRelation) {
|
|
throw new InvalidPayloadError({
|
|
reason: `Provided diff is trying to delete relation "${relation}" but it does not exist. Please generate a new diff and try again`,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
throw new InvalidPayloadError({
|
|
reason: `Provided hash does not match the current instance's schema hash, indicating the schema has changed after this diff was generated. Please generate a new diff and try again`,
|
|
});
|
|
}
|