@skimp/json-api
Version:
The json-api module for the skimp domain modelling framework
54 lines • 2.12 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@cleavera/utils");
const core_1 = require("@skimp/core");
const router_1 = require("@skimp/router");
const request_not_valid_data_exception_1 = require("../exception/request-not-valid-data.exception");
const serialiser_1 = require("./serialiser");
class Api {
constructor() {
this.serialiser = new serialiser_1.Serialiser();
}
respond(response, model, _location, created) {
let out;
if (Array.isArray(model)) {
out = this.serialiser.serialiseList(model);
response.setAllow(true, false, false);
}
else {
const location = core_1.MODEL_REGISTER.getLocation(model);
if (utils_1.$isNull(location)) {
throw new router_1.NoLocationRegisteredException(model);
}
out = this.serialiser.serialiseModel(model, location);
if (created) {
response.statusCode = core_1.ResponseCode.CREATED;
response.location = location.toString();
}
response.setAllow(location.isResource(), location.isEntity(), location.isEntity());
}
response.write(out, 'application/json');
response.commit();
}
error(response, code, errors = null) {
response.statusCode = code;
if (!utils_1.$isNull(errors) && errors.length) {
response.write(this.serialiser.error(errors));
}
response.commit();
}
deserialise(content, location) {
const json = JSON.parse(content);
if (!Api.isData(json)) {
throw new request_not_valid_data_exception_1.RequestNotValidDataException(json);
}
const model = this.serialiser.deserialise(json);
core_1.MODEL_REGISTER.setLocation(model, location);
return model;
}
static isData(json) {
return 'data' in json && 'attributes' in json.data && 'type' in json.data;
}
}
exports.Api = Api;
//# sourceMappingURL=api.js.map