app.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 create_app(project_root, storage, runtime)
  34. {
  35. const app = express();
  36. app.use(cors());
  37. app.use(bodyParser.json());
  38. // FIXME app.use(bodyParser.urlencoded({ extended: true }));
  39. // Load & extend/configure API docs
  40. var api = yaml.safeLoad(fs.readFileSync(
  41. path.resolve(project_root, 'api-base.yml')));
  42. api['x-express-openapi-additional-middleware'] = [validateResponses];
  43. api['x-express-openapi-validation-strict'] = true;
  44. api = pagination.openapi(api);
  45. openapi.initialize({
  46. apiDoc: api,
  47. app: app,
  48. paths: path.resolve(project_root, 'paths'),
  49. docsPath: '/swagger.json',
  50. consumesMiddleware: {
  51. 'multipart/form-data': fileUploads
  52. },
  53. dependencies: {
  54. storage: storage,
  55. runtime: runtime,
  56. },
  57. });
  58. // If no other handler gets triggered (errors), respond with the
  59. // error serialized to JSON.
  60. app.use(function(err, req, res, next) {
  61. res.status(err.status).json(err);
  62. });
  63. return app;
  64. }
  65. module.exports = create_app;