@codesnippets/codesnippets
Version:
Open source code snippets and examples.
48 lines (41 loc) • 1.31 kB
text/typescript
import crypto = require('crypto');
import fs = require('fs');
import path = require('path');
import { Language } from './language';
const syncRequest = require('sync-request');
export class Snippet {
public constructor(public readonly name: string, private language: Language, private object: any) {}
private doRequest(): string {
let res = syncRequest('GET', this.object.url);
return res.body;
}
private initDir() {
if (!fs.existsSync(path.resolve(path.join(__dirname, '../', this.language.name)))) {
fs.mkdirSync(path.resolve(path.join(__dirname, '../', this.language.name.toLowerCase())));
}
}
private getFile() {
this.initDir();
let 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
*/
public get(): string {
if (!fs.existsSync(this.object.path)) {
return this.getFile();
} else {
let data = fs.readFileSync(this.object.path).toString();
let hash = crypto.createHash('sha1');
hash.update(data);
if (hash.digest('hex') !== this.object.sum) {
return this.getFile();
} else {
return data;
}
}
}
}