{"size": 1570, "ext": "js", "max_stars_repo_path": "core/server/api/canary/utils/validators/input/posts.js", "max_stars_repo_name": "Sen-442b/Ghost", "max_stars_repo_stars_event_min_datetime": "2015-01-01T01:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:52:13.000Z", "max_issues_repo_path": "core/server/api/canary/utils/validators/input/posts.js", "max_issues_repo_name": "Sen-442b/Ghost", "max_issues_repo_issues_event_min_datetime": "2015-01-01T12:29:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:58:30.000Z", "max_forks_repo_path": "core/server/api/canary/utils/validators/input/posts.js", "max_forks_repo_name": "Sen-442b/Ghost", "max_forks_repo_forks_event_min_datetime": "2015-01-01T05:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:47:31.000Z"}
{"max_stars_count": 31697, "max_issues_count": 6768, "max_forks_count": 10906, "avg_line_length": 32.7083333333, "max_line_length": 108, "alphanum_fraction": 0.5891719745}
const jsonSchema = require('../utils/json-schema');
const models = require('../../../../../models');
const {ValidationError} = require('@tryghost/errors');
const tpl = require('@tryghost/tpl');

const messages = {
    invalidVisibilityFilter: 'Invalid filter in visibility_filter property'
};

const validateVisibility = async function (frame) {
    if (!frame.data.posts || !frame.data.posts[0]) {
        return Promise.resolve();
    }

    // validate visibility - not done at schema level because this can be an NQL query so needs model access
    const visibility = frame.data.posts[0].visibility;
    const visibilityFilter = frame.data.posts[0].visibility_filter;
    if (visibility) {
        if (!['public', 'members', 'paid'].includes(visibility)) {
            // check filter is valid
            try {
                await models.Member.findPage({filter: visibilityFilter, limit: 1});
                return Promise.resolve();
            } catch (err) {
                return Promise.reject(new ValidationError({
                    message: tpl(messages.invalidVisibilityFilter),
                    property: 'visibility_filter'
                }));
            }
        }

        return Promise.resolve();
    }
};

module.exports = {
    add(apiConfig, frame) {
        return jsonSchema.validate(...arguments).then(() => {
            return validateVisibility(frame);
        });
    },
    edit(apiConfig, frame) {
        return jsonSchema.validate(...arguments).then(() => {
            return validateVisibility(frame);
        });
    }
};
