app.js 2.3 KB

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