@openevstack/ocpp-rpc
Version:
⚡ A lightweight, production-ready RPC server built with Express and WebSocket for handling OCPP-based EV charger communication. Part of the OpenEVStack ecosystem.
61 lines (60 loc) • 2.24 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createValidator = exports.Validator = void 0;
const ajv_1 = __importDefault(require("ajv"));
const ajv_formats_1 = __importDefault(require("ajv-formats"));
const rpcError_1 = require("../rpcError");
const error_codes_1 = require("./error-codes");
class Validator {
constructor(subprotocol, ajv) {
this._subprotocol = subprotocol;
this._ajv = ajv;
}
get subprotocol() {
return this._subprotocol;
}
validate(schemaId, params) {
var _a, _b;
const validator = this._ajv.getSchema(schemaId);
if (!validator) {
throw (0, rpcError_1.createRPCError)("ProtocolError", `Schema '${schemaId}' is missing from subprotocol schema '${this._subprotocol}'`);
}
const valid = validator(params);
if (!valid && ((_a = validator.errors) === null || _a === void 0 ? void 0 : _a.length)) {
const [first] = validator.errors;
const rpcErrorCode = (_b = error_codes_1.errorCodeLUT[first.keyword]) !== null && _b !== void 0 ? _b : "FormatViolation";
throw (0, rpcError_1.createRPCError)(rpcErrorCode, this._ajv.errorsText(validator.errors), {
errors: validator.errors,
data: params,
});
}
return true;
}
}
exports.Validator = Validator;
function createValidator(subprotocol, json) {
const ajv = new ajv_1.default({ strictSchema: false });
(0, ajv_formats_1.default)(ajv);
ajv.addSchema(json);
ajv.removeKeyword("multipleOf");
ajv.addKeyword({
keyword: "multipleOf",
type: "number",
compile(schema) {
return (data) => {
const result = data / schema;
const epsilon = 1e-6;
return Math.abs(Math.round(result) - result) < epsilon;
};
},
errors: false,
metaSchema: {
type: "number",
},
});
return new Validator(subprotocol, ajv);
}
exports.createValidator = createValidator;