@ephys/graphql-joi-directives
Version:
Adds Joi-powered constraint directive for GraphQL
61 lines (60 loc) • 2.39 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildJoiFloatDirectiveTypedef = exports.buildJoiFloatDirective = void 0;
const graphql_1 = require("graphql");
const joi_1 = __importDefault(require("joi"));
const _internal_1 = require("./_internal");
class JoiConstrainedFloat extends _internal_1.JoiConstrainedScalar {
buildJoi(fieldName, args) {
let schema = joi_1.default.number().integer().label(fieldName);
for (const argKey of Object.keys(args)) {
const argVal = args[argKey];
switch (argKey) {
case 'min':
schema = schema.min(argVal);
break;
case 'max':
schema = schema.max(argVal);
break;
case 'minExclusive':
schema = schema.greater(argVal);
break;
case 'maxExclusive':
schema = schema.less(argVal);
break;
case 'precision':
schema = schema.precision(argVal);
break;
default:
throw new Error(`Unsupported argument ${argKey}.`);
}
}
return schema;
}
}
function buildJoiFloatDirective(directiveName) {
return _internal_1.buildJoiDirective(directiveName, graphql_1.GraphQLFloat, JoiConstrainedFloat);
}
exports.buildJoiFloatDirective = buildJoiFloatDirective;
function buildJoiFloatDirectiveTypedef(directiveName) {
return `
directive @${directiveName}(
# value must be greater than or equal to {min}
min: Float,
# value must be less than or equal to {max}
max: Float,
# value must be greater than {minExclusive}
# Joi: number.greater - https://joi.dev/api/?v=17.4.0#numbergreaterlimit
minExclusive: Float,
# value must be less than {maxExclusive}
# Joi: number.less - https://joi.dev/api/?v=17.4.0#numberlesslimit
maxExclusive: Float,
# sets a maximum number of decimal places allowed
precision: Int,
) on INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION
`;
}
exports.buildJoiFloatDirectiveTypedef = buildJoiFloatDirectiveTypedef;