|
| 1 | +import { get } from 'lodash' |
| 2 | +import Field from '../Field' |
| 3 | +import Resource from '../Resource' |
| 4 | + |
| 5 | +String.prototype.capitalize = function() { |
| 6 | + return this.charAt(0).toUpperCase() + this.slice(1); |
| 7 | +} |
| 8 | + |
| 9 | +const onlyUnique = (value, index, self) => self.indexOf(value) === index; |
| 10 | + |
| 11 | +export const removeTrailingSlash = url => { |
| 12 | + if (/\/$/.test(url)) { |
| 13 | + url = url.slice(0, -1) |
| 14 | + } |
| 15 | + return url |
| 16 | +} |
| 17 | + |
| 18 | +export default function(response, entrypointUrl) { |
| 19 | + const paths = Object.keys(response.paths).map(item => item.replace(`/{id}`, ``)).filter(onlyUnique); |
| 20 | + |
| 21 | + const resources = paths.map(item => { |
| 22 | + |
| 23 | + const name = item.replace(`/`, ``); |
| 24 | + const url = removeTrailingSlash(entrypointUrl) + item; |
| 25 | + const firstMethod = Object.keys(response.paths[item])[0]; |
| 26 | + const title = response.paths[item][firstMethod]['tags'][0]; |
| 27 | + const fieldNames = Object.keys(response.definitions[title].properties); |
| 28 | + |
| 29 | + const fields = fieldNames.map(fieldName => new Field(fieldName, |
| 30 | + { |
| 31 | + id: `http://schema.org/${fieldName}`, |
| 32 | + range: null, |
| 33 | + reference: null, |
| 34 | + required: !!response.definitions[title].required.find(value => value === fieldName), |
| 35 | + description: get(response.definitions[title].properties[fieldName], `description`, ``), |
| 36 | + }, |
| 37 | + )); |
| 38 | + |
| 39 | + return new Resource( |
| 40 | + name, |
| 41 | + url, |
| 42 | + { |
| 43 | + id: `http://schema.org/` + title, |
| 44 | + title, |
| 45 | + fields, |
| 46 | + readableFields: fields, |
| 47 | + writableFields: fields, |
| 48 | + } |
| 49 | + ) |
| 50 | + }) |
| 51 | + |
| 52 | + return resources |
| 53 | +} |
0 commit comments