-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
69 lines (60 loc) · 2.18 KB
/
index.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
const port = 3000;
const connect = require( 'connect' );
const http = require( 'http' );
const serveStatic = require( 'serve-static' );
const busboy = require( 'connect-busboy' );
const enketoValidator = require( 'enketo-validate' );
const odkValidator = require( './src/odk-validate' );
let app = connect();
app.use( serveStatic( 'public' ) );
app.use( busboy() );
// Receive an XForm file and validate it in both validators
app.use( '/validate', ( req, res, next ) => {
let enketo = {};
let odk = {};
let xform = '';
if ( req.busboy && req.url === '/' ) {
req.busboy.on( 'file', ( fieldname, file ) => {
file
.on( 'data', d => xform += d )
.setEncoding( 'utf8' );
} );
req.busboy.on( 'finish', async() => {
try {
enketo = await enketoValidator.validate( xform );
}
catch( e ){
console.error( 'something went wrong during Enketo Validation', e );
enketo.errors = [ e ];
}
try {
odk = await odkValidator.validate( xform );
}
catch ( e ){
console.error( 'something went wrong during ODK Validation', e );
odk.errors = [ e ];
}
res.writeHead( 200, { 'Content-Type': 'application/json' } );
res.write( JSON.stringify( { enketo, odk } ) );
res.end();
} );
req.pipe( req.busboy );
} else if ( req.busboy && req.url === '/oc' ) {
req.busboy.on( 'file', ( fieldname, file ) => {
file
.on( 'data', d => xform += d )
.setEncoding( 'utf8' );
} );
req.busboy.on( 'finish', async() => {
const enketo = await enketoValidator.validate( xform, { openclinica: true } );
res.writeHead( 200, { 'Content-Type': 'application/json' } );
res.write( JSON.stringify( { enketo } ) );
res.end();
} );
req.pipe( req.busboy );
} else {
next();
}
} );
http.createServer( app ).listen( port );
console.log( `launched server on port: ${port}` );