controllers/reasoningController.js

/**
 * This controller handles the logic for the reasoning routes, works in conjunction with ../reasoning/index.json
 * @module Controllers/ReasoningController
 */

const ReasoningService = require('../services/reasoning.js')
const FileService = require('../services/n3FileService.js')
const SolidService = require('../services/solidService.js')

const indexData = require('../reasoning/index.json')

// error handling
const Boom = require('@hapi/boom')

/**
* Get the query and data from the index.json in /reasoning folder for the route that was called
* Perform the required query and send results back to user
*/
exports.index = async (req, res, next) => {
  // get the query and data locations from the json file, depending on the plan name that was provided
  const planName = req.params.plan
  const meta = indexData.features[planName]

  if (meta == null) {
    return next(Boom.notFound('Route does not exist.'))
  }
  // initialize the fileservice
  const fileService = new FileService()
  let solidService = null
  if (req.method === 'GET') {
    meta.inference.data.push('./reasoning/profile/profileInfo.n3')
  } else {
    solidService = new SolidService()

    // solid specific cases
    solidService.uploadProfileToPersonalStorage(req.body)
    solidService.injectUserStorageLocation(meta.inference)
  }
  if (solidService !== null && solidService.validated !== null) {
    return next(Boom.notFound('Incorrect data structure, problem occured on line ' + solidService.validated.context.line))
  }

  // Here comes the all the DAG invocation
  ReasoningService.eyePromise(meta.inference)
    .then((queryResult) => {
      // convert turtle result to json-ld
      if (Object.prototype.hasOwnProperty.call(req.headers, 'accept') && req.headers.accept === 'text/plain') {
        res.send(queryResult)
      } else {
        const jsonResult = fileService.stringToJSONLD(queryResult)

        // if meta contains inference.output, we write the contents to a file in the output
        if (meta.inference.output != null && meta.inference.output !== '') {
          // get file from meta
          const file = meta.inference.output

          // write the reasoning result to the file
          fileService.writeStringToFile(file, queryResult)
            .catch(err => console.log(err))
        }

        res.send(jsonResult)
      }
    })
    .catch((error) => {
      next(error)
    })
    .finally(() => {
      // clean up the user data
      if (solidService !== null) {
        solidService.removeUserData()
      }
    })
}