app.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * This file is part of the storage node for the Joystream project.
  3. * Copyright (C) 2019 Joystream Contributors
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. 'use strict'
  19. // Node requires
  20. const fs = require('fs')
  21. const path = require('path')
  22. // npm requires
  23. const express = require('express')
  24. const openapi = require('express-openapi')
  25. const bodyParser = require('body-parser')
  26. const cors = require('cors')
  27. const yaml = require('js-yaml')
  28. // Project requires
  29. const validateResponses = require('./middleware/validate_responses')
  30. const fileUploads = require('./middleware/file_uploads')
  31. const pagination = require('@joystream/storage-utils/pagination')
  32. // Configure app
  33. function createApp(projectRoot, storage, runtime, ipfsHttpGatewayUrl, anonymous) {
  34. const app = express()
  35. app.use(cors())
  36. app.use(bodyParser.json())
  37. // FIXME app.use(bodyParser.urlencoded({ extended: true }));
  38. // Load & extend/configure API docs
  39. let api = yaml.safeLoad(fs.readFileSync(path.resolve(projectRoot, 'api-base.yml')))
  40. api['x-express-openapi-additional-middleware'] = [validateResponses]
  41. api['x-express-openapi-validation-strict'] = true
  42. api = pagination.openapi(api)
  43. openapi.initialize({
  44. apiDoc: api,
  45. app,
  46. paths: path.resolve(projectRoot, 'paths'),
  47. docsPath: '/swagger.json',
  48. consumesMiddleware: {
  49. 'multipart/form-data': fileUploads,
  50. },
  51. dependencies: {
  52. storage,
  53. runtime,
  54. ipfsHttpGatewayUrl,
  55. anonymous,
  56. },
  57. })
  58. // If no other handler gets triggered (errors), respond with the
  59. // error serialized to JSON.
  60. // Disable lint because we need such function signature.
  61. // eslint-disable-next-line no-unused-vars
  62. app.use(function (err, req, res, next) {
  63. res.status(err.status).json(err)
  64. })
  65. return app
  66. }
  67. module.exports = createApp