Refactor contribution serializer and validation
This commit is contained in:
@@ -1,45 +1,24 @@
|
||||
const schemas = require('kosmos-schemas');
|
||||
const validator = require('../utils/validator');
|
||||
|
||||
/**
|
||||
* Handle serialization for JSON-LD object of the contribution, according to
|
||||
* https://github.com/67P/kosmos-schemas/blob/master/schemas/contribution.json
|
||||
* Serialization and validation for JSON-LD document of the contribution.
|
||||
*
|
||||
* @class
|
||||
* @public
|
||||
*/
|
||||
class Contribution {
|
||||
/**
|
||||
* Deserialize JSON to object
|
||||
*
|
||||
* @method
|
||||
* @public
|
||||
*/
|
||||
static deserialize(serialized) {
|
||||
let {
|
||||
date,
|
||||
time,
|
||||
kind,
|
||||
description,
|
||||
details,
|
||||
url,
|
||||
} = JSON.parse(serialized.toString('utf8'));
|
||||
|
||||
return {
|
||||
date,
|
||||
time,
|
||||
kind,
|
||||
description,
|
||||
details,
|
||||
url,
|
||||
ipfsData: serialized,
|
||||
};
|
||||
constructor(attrs) {
|
||||
Object.keys(attrs).forEach(a => this[a] = attrs[a]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize object to JSON
|
||||
*
|
||||
* @method
|
||||
* @public
|
||||
*/
|
||||
static serialize(deserialized) {
|
||||
/**
|
||||
* Serialize object to JSON
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
serialize () {
|
||||
let {
|
||||
contributorIpfsHash,
|
||||
date,
|
||||
@@ -48,7 +27,7 @@ class Contribution {
|
||||
description,
|
||||
url,
|
||||
details
|
||||
} = deserialized;
|
||||
} = this;
|
||||
|
||||
let data = {
|
||||
"@context": "https://schema.kosmos.org",
|
||||
@@ -70,6 +49,44 @@ class Contribution {
|
||||
// Write it pretty to ipfs
|
||||
return JSON.stringify(data, null, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate serialized data against schema
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
validate () {
|
||||
const serialized = JSON.parse(this.serialize());
|
||||
const valid = validator.validate(serialized, schemas['contribution']);
|
||||
return valid ? Promise.resolve() : Promise.reject(validator.error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize JSON to object
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
static deserialize (serialized) {
|
||||
let {
|
||||
date,
|
||||
time,
|
||||
kind,
|
||||
description,
|
||||
details,
|
||||
url,
|
||||
} = JSON.parse(serialized.toString('utf8'));
|
||||
|
||||
return {
|
||||
date,
|
||||
time,
|
||||
kind,
|
||||
description,
|
||||
details,
|
||||
url,
|
||||
ipfsData: serialized,
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
module.exports = Contribution;
|
||||
|
||||
Reference in New Issue
Block a user