forked from pensoft/refindit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
format.js
87 lines (82 loc) · 2.2 KB
/
format.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*jslint node: true, nomen: true, vars: true, white: true, devel: true, stupid: true */
/*global craft: false, formatReference: false, common2csl: false */
"use strict";
module.exports = function (app){
app.get('/format', craft);
console.log("Module 'format' loaded");
};
var config = require('./config');
var p = require('./debug')().p;
function craft(req, res) {
var q = req.query;
var style = q.style;
var ref = q.ref;
var result = formatReference(ref, style);
res.setHeader('Access-Control-Allow-Origin', '*');
if (result) {
res.send(result);
}
else {
res.sendfile(config.apidoc);
}
}
function common2csl(ref) {
try {
ref = JSON.parse(ref);
}
catch (e) {
return {};
}
var authors = [];
if (Array.isArray(ref.authors)) {
authors = ref.authors.map(function (author) {
return { "family" : author[1],
"given" : author[0]};
});
}
return {
"id": "ITEM-1",
author: authors,
DOI: ref.doi,
title: ref.title,
issued: { "date-parts": [[ parseInt(ref.year, 10)]] },
"container-title": ref.publishedIn,
volume: ref.volume,
issue: ref.issue,
page: ref.spage + '-' + ref.epage
};
}
function formatReference(ref, styleName) {
var my_ids = ["ITEM-1"];
var dontSort = true;
var CSL = require('./format/citeprocnode');
var sys = {};
var fs = require('fs');
var lang = 'en-US';
var result = common2csl(ref);
var stylePath = config.stylesPath + styleName + '.csl';
if (!fs.existsSync(stylePath)) {
return "ERROR: The specified style doesn't exist on the server.";
}
if (Object.keys(result).length === 0) {
return 'ERROR: Unable to parse the reference as JSON.';
}
sys.retrieveLocale = function(lang){
fs.readFileSync(config.localesPath + 'locales-' + lang + '.xml', 'utf8');
};
sys.getAbbreviations = function(name){
return { default: {} }[name];
};
sys.retrieveItem = function(id){
return result;
};
var style = fs.readFileSync(stylePath, 'utf8');
var citeproc = new CSL.createEngine(sys, style, lang);
citeproc.updateUncitedItems( my_ids, dontSort);
var mybib = citeproc.makeBibliography();
var html='';
if (mybib){
html = mybib[1][0];
}
return html;
}