2019-01-27 19:28:20 +08:00
const repository = require ( '../services/repository' ) ;
const log = require ( '../services/log' ) ;
2019-01-27 22:47:40 +08:00
const fileUploadService = require ( './api/file_upload' ) ;
2019-01-27 19:28:20 +08:00
const scriptService = require ( '../services/script' ) ;
function register ( router ) {
2019-03-25 05:41:53 +08:00
// explicitly no CSRF middleware since it's meant to allow integration from external services
2019-01-27 19:28:20 +08:00
router . all ( '/custom/:path*' , async ( req , res , next ) => {
2019-01-27 22:47:40 +08:00
// express puts content after first slash into 0 index element
const path = req . params . path + req . params [ 0 ] ;
const attrs = await repository . getEntities ( "SELECT * FROM attributes WHERE isDeleted = 0 AND type = 'label' AND name IN ('customRequestHandler', 'customResourceProvider')" ) ;
2019-01-27 19:28:20 +08:00
for ( const attr of attrs ) {
const regex = new RegExp ( attr . value ) ;
2019-01-27 23:37:18 +08:00
let match ;
2019-01-27 19:28:20 +08:00
try {
2019-01-27 23:37:18 +08:00
match = path . match ( regex ) ;
2019-01-27 19:28:20 +08:00
}
catch ( e ) {
log . error ( ` Testing path for label ${ attr . attributeId } , regex= ${ attr . value } failed with error ` + e . stack ) ;
2019-01-27 23:37:18 +08:00
continue ;
2019-01-27 19:28:20 +08:00
}
2019-01-27 23:37:18 +08:00
if ( ! match ) {
continue ;
}
if ( attr . name === 'customRequestHandler' ) {
const note = await attr . getNote ( ) ;
log . info ( ` Handling custom request " ${ path } " with note ${ note . noteId } ` ) ;
2019-02-03 18:15:32 +08:00
try {
await scriptService . executeNote ( note , {
pathParams : match . slice ( 1 ) ,
req ,
res
} ) ;
}
catch ( e ) {
log . error ( ` Custom handler ${ note . noteId } failed with ${ e . message } ` ) ;
res . status ( 500 ) . send ( e . message ) ;
}
2019-01-27 23:37:18 +08:00
}
else if ( attr . name === 'customResourceProvider' ) {
await fileUploadService . downloadNoteFile ( attr . noteId , res ) ;
}
else {
throw new Error ( "Unrecognized attribute name " + attr . name ) ;
}
return ; // only first handler is executed
2019-01-27 19:28:20 +08:00
}
2019-01-27 22:47:40 +08:00
const message = ` No handler matched for custom ${ path } request. ` ;
log . info ( message ) ;
res . status ( 404 ) . send ( message ) ;
2019-01-27 19:28:20 +08:00
} ) ;
}
module . exports = {
register
} ;