Skip to content
Snippets Groups Projects
classifications.js 1.54 KiB
Newer Older
const publicStatus = new Set(['accepted'])
const privateStatus = new Set(['pending', 'rejected'])

const { Sequelize, ClassificationRoot } = require('database/models')
const NotFoundError = require("core/errors/NotFoundError");
const UnauthorizedError = require("core/errors/UnauthorizedError");
const InputValidationError = require("core/errors/InputValidationError");

exports.listRoots = async ctx => {
	const { status = '', limit = 25, after = null } = ctx.query

	const requestedStatus = status.split(',')
		.map(s => s.trim())
		.filter(s => publicStatus.has(s) || privateStatus.has(s))

	const query = {
		order: ['metric_id', 'created_at'],
		where: {
			status: {
				[Sequelize.Op.in]: requestedStatus,
			}
		},
		limit,
	}

	const count = await ClassificationRoot.count(query)

	if (after) {
		query.where.metric_id = {
			[Sequelize.Op.gt]: after,
		}
	}

	const roots = await ClassificationRoot.findAll(query)

	ctx.body = {
		roots,
		meta: {
			total: count,
		}
	}
}

exports.putRootStatus = async ctx => {
	const user = await ctx.services['core.auth'].getUser()

	if (!user) {
		throw new UnauthorizedError()
	}

	if (ctx.models.classification == null) {
		throw new NotFoundError('Classification Root')
	}

	const { status } = ctx.request.body
	const { classification } = ctx.models

	if (!publicStatus.has(status) && !privateStatus.has(status)) {
		throw new InputValidationError(['status'])
	}

	classification.status = status
	classification.meta = {
		approved_by: user.id,
	}
	await classification.save()

	ctx.body = {
		root: classification,
	}
}