@codesnippets/codesnippets
Version:
Open source code snippets and examples.
52 lines (51 loc) • 1.73 kB
JavaScript
"use strict";
exports.__esModule = true;
exports.Snippet = void 0;
var crypto = require("crypto");
var fs = require("fs");
var path = require("path");
var syncRequest = require('sync-request');
var Snippet = /** @class */ (function () {
function Snippet(name, language, object) {
this.name = name;
this.language = language;
this.object = object;
}
Snippet.prototype.doRequest = function () {
var res = syncRequest('GET', this.object.url);
return res.body;
};
Snippet.prototype.initDir = function () {
if (!fs.existsSync(path.resolve(path.join(__dirname, '../', this.language.name)))) {
fs.mkdirSync(path.resolve(path.join(__dirname, '../', this.language.name.toLowerCase())));
}
};
Snippet.prototype.getFile = function () {
this.initDir();
var data = this.doRequest().toString();
fs.writeFileSync(path.resolve(path.join(__dirname, '../', this.object.path)), data);
return data;
};
/**
* Gets the file contents of the snippet.
* @param callback called when the snippet is retrieved
*/
Snippet.prototype.get = function () {
if (!fs.existsSync(this.object.path)) {
return this.getFile();
}
else {
var data = fs.readFileSync(this.object.path).toString();
var hash = crypto.createHash('sha1');
hash.update(data);
if (hash.digest('hex') !== this.object.sum) {
return this.getFile();
}
else {
return data;
}
}
};
return Snippet;
}());
exports.Snippet = Snippet;