Skip to content

Commit

Permalink
temp(core): add joi when
Browse files Browse the repository at this point in the history
  • Loading branch information
Drapegnik committed Aug 18, 2019
1 parent d871ec7 commit d6b05d4
Showing 1 changed file with 26 additions and 26 deletions.
52 changes: 26 additions & 26 deletions src/api/article/article.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,18 @@ const joiArticleSchema = Joi.object({
.default(null),
active: Joi.boolean().default(true),
// Images are as described in 'covers' guide by Vitalik.
images: Joi.object().required(),
images: Joi.object({
page: Joi.image(),
horizontal: Joi.image(),
})
.when('type', {
is: 'text',
then: Joi.object({
vertical: Joi.image(),
}),
})
.meta({ type: 'Object' })
.required(),
// Can only be present when Article type is video.
video: joiVideoSchema,
color: Joi.color().default('000000'),
Expand All @@ -63,6 +74,20 @@ const ArticleSchema = joiToMongoose(joiArticleSchema, {
usePushEach: true,
});

ArticleSchema.pre('validate', function(next) {
// eslint-disable-next-line no-underscore-dangle
const { error } = Joi.validate(omit(this._doc, '_id'), joiArticleSchema);
if (error) {
const errors = {};
error.details.forEach(({ path, type }) => {
set(errors, path, type);
});

next(new ValidationError(errors));
}
next();
});

// TODO: replace with joi?
ArticleSchema.pre('validate', function(next) {
if (this.type === 'video') {
Expand All @@ -84,31 +109,6 @@ ArticleSchema.pre('validate', function(next) {
next();
});

const IMAGES_SCHEMA = {
text: Joi.object({
page: Joi.image(),
horizontal: Joi.image(),
vertical: Joi.image(),
}),
video: Joi.object({
page: Joi.image(),
horizontal: Joi.image(),
}),
};

ArticleSchema.pre('validate', function(next) {
const { error } = Joi.validate(this.images, IMAGES_SCHEMA[this.type].required());
if (error !== null) {
const errors = {};
error.details.forEach(({ path, type }) => {
set(errors, ['images', ...path], type);
});

next(new ValidationError(errors));
}
next();
});

// includeCollection flag here is to be able to avoid including collections
// in case we're serializing an article into the ArticleCollection object..
export const serializeArticle = (article, { includeCollection = true } = {}) => {
Expand Down

0 comments on commit d6b05d4

Please sign in to comment.