Schemas.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. Copyright (C) 2017 Cloudbase Solutions SRL
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. // @flow
  15. import { ConnectionSchemaPlugin, OptionsSchemaPlugin } from '../plugins/endpoint'
  16. import type { Schema } from '../types/Schema'
  17. import type { Endpoint } from '../types/Endpoint'
  18. class SchemaParser {
  19. static storedConnectionsSchemas = {}
  20. static connectionSchemaToFields(provider: string, schema: Schema) {
  21. if (!this.storedConnectionsSchemas[provider]) {
  22. this.storedConnectionsSchemas[provider] = schema
  23. }
  24. let parsers = ConnectionSchemaPlugin[provider] || ConnectionSchemaPlugin.default
  25. let fields = parsers.parseSchemaToFields(schema)
  26. return fields
  27. }
  28. static optionsSchemaToFields(provider: string, schema: any) {
  29. let parser = OptionsSchemaPlugin[provider] || OptionsSchemaPlugin.default
  30. let schemaRoot = schema.oneOf ? schema.oneOf[0] : schema
  31. let fields = parser.parseSchemaToFields(schemaRoot, schema.definitions)
  32. fields.sort((a, b) => {
  33. if (a.required && !b.required) {
  34. return -1
  35. }
  36. if (!a.required && b.required) {
  37. return 1
  38. }
  39. return a.name.localeCompare(b.name)
  40. })
  41. return fields
  42. }
  43. static fieldsToPayload(data: { [string]: any }) {
  44. let storedSchema = this.storedConnectionsSchemas[data.type] || this.storedConnectionsSchemas.general
  45. let parsers = ConnectionSchemaPlugin[data.type] || ConnectionSchemaPlugin.default
  46. let payload = parsers.parseFieldsToPayload(data, storedSchema)
  47. return payload
  48. }
  49. static parseConnectionResponse(endpoint: Endpoint) {
  50. let parseConnectionResponse = ConnectionSchemaPlugin[endpoint.type] && ConnectionSchemaPlugin[endpoint.type].parseConnectionResponse
  51. if (!parseConnectionResponse) {
  52. return endpoint
  53. }
  54. return parseConnectionResponse(endpoint)
  55. }
  56. }
  57. export { SchemaParser }