All files / lib/swagger paths.js

10.78% Statements 11/102
0% Branches 0/81
0% Functions 0/11
11.46% Lines 11/96
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346  1x 1x 1x       1x                     1x                                       1x                                                                                                           1x                                                                                                                             1x                                                                                                                                                                                                                                                                                                           1x               1x                                 1x                              
'use strict'
const swaggerPaths = module.exports = { }
const jsonApi = require('../../')
const _ = {
  uniq: require('lodash.uniq')
}
 
swaggerPaths.getPathDefinitions = () => {
  const paths = { }
 
  for (const resourceName in jsonApi._resources) {
    const resourceConfig = jsonApi._resources[resourceName]
    swaggerPaths._addPathDefinition(paths, resourceConfig)
  }
 
  return paths
}
 
swaggerPaths._addPathDefinition = (paths, resourceConfig) => {
  if (!paths || !resourceConfig) return undefined
  const resourceName = resourceConfig.resource
 
  swaggerPaths._addBasicPaths(paths, resourceName, resourceConfig)
 
  Object.keys(resourceConfig.attributes).filter(relationName => {
    let relation = resourceConfig.attributes[relationName]
    relation = relation._settings
    if (!relation || relation.__as) return false
    relation = (relation.__many || relation.__one)[0]
    return (jsonApi._resources[relation] && jsonApi._resources[relation].handlers.find)
  }).forEach(relationName => {
    let relation = resourceConfig.attributes[relationName]
    relation = (relation._settings.__one || relation._settings.__many)[0]
 
    swaggerPaths._addDeepPaths(paths, resourceName, resourceConfig, relationName, relation)
  })
}
 
swaggerPaths._addBasicPaths = (paths, resourceName, resourceConfig) => {
  const genericPaths = { }
  const specificPaths = { }
  paths[`/${resourceName}`] = genericPaths
  paths[`/${resourceName}/{id}`] = specificPaths
 
  if (resourceConfig.handlers.search) {
    genericPaths.get = swaggerPaths._getPathOperationObject({
      handler: 'search',
      resourceName,
      description: `Search for ${resourceName}`,
      parameters: resourceConfig.searchParams,
      hasPathId: false
    })
  }
 
  if (resourceConfig.handlers.create) {
    genericPaths.post = swaggerPaths._getPathOperationObject({
      handler: 'create',
      resourceName,
      description: `Create a new instance of ${resourceName}`,
      parameters: resourceConfig.attributes,
      hasPathId: false
    })
  }
 
  if (resourceConfig.handlers.find) {
    specificPaths.get = swaggerPaths._getPathOperationObject({
      handler: 'find',
      resourceName,
      description: `Get a specific instance of ${resourceName}`,
      hasPathId: true
    })
  }
 
  if (resourceConfig.handlers.delete) {
    specificPaths.delete = swaggerPaths._getPathOperationObject({
      handler: 'delete',
      resourceName,
      description: `Delete an instance of ${resourceName}`,
      hasPathId: true
    })
  }
 
  if (resourceConfig.handlers.update) {
    specificPaths.patch = swaggerPaths._getPathOperationObject({
      handler: 'update',
      resourceName,
      description: `Update an instance of ${resourceName}`,
      hasPathId: true
    })
  }
}
 
swaggerPaths._addDeepPaths = (paths, resourceName, resourceConfig, relationName, relation) => {
  const relationType = resourceConfig.attributes[relationName]._settings.__many ? 'many' : 'one'
 
  if (resourceConfig.handlers.find) {
    paths[`/${resourceName}/{id}/${relationName}`] = {
      get: swaggerPaths._getPathOperationObject({
        handler: 'find',
        description: `Get the ${relationName} instance${relationType === 'many' ? 's' : ''} of a specific instance of ${resourceName}`,
        resourceName: relation,
        hasPathId: true
      })
    }
  }
 
  const relationPaths = { }
  paths[`/${resourceName}/{id}/relationships/${relationName}`] = relationPaths
  const description = `the ${relationName} relationship of a specific instance of ${resourceName}`
 
  if (resourceConfig.handlers.find) {
    relationPaths.get = swaggerPaths._getPathOperationObject({
      description: `Get ${description}`,
      handler: 'find',
      resourceName: relation,
      relationType,
      extraTags: resourceName,
      hasPathId: true
    })
  }
 
  if (resourceConfig.handlers.update) {
    relationPaths.post = swaggerPaths._getPathOperationObject({
      description: `Create ${description}`,
      handler: 'create',
      resourceName: relation,
      relationType,
      extraTags: resourceName,
      hasPathId: true
    })
  }
 
  if (resourceConfig.handlers.update) {
    relationPaths.patch = swaggerPaths._getPathOperationObject({
      description: `Update ${description}`,
      handler: 'update',
      resourceName: relation,
      relationType,
      extraTags: resourceName,
      hasPathId: true
    })
  }
 
  if (resourceConfig.handlers.update) {
    relationPaths.delete = swaggerPaths._getPathOperationObject({
      description: `Delete ${description}`,
      handler: 'delete',
      resourceName: relation,
      relationType,
      extraTags: resourceName,
      hasPathId: true
    })
  }
}
 
swaggerPaths._getPathOperationObject = options => {
  const pathDefinition = {
    tags: [ options.resourceName ],
    description: options.description,
    parameters: [ ],
    responses: {
      '200': {
        description: `${options.resourceName} ${options.handler} response`,
        schema: {
          type: 'object',
          required: [ 'jsonapi', 'meta', 'links' ],
          properties: {
            jsonapi: {
              type: 'object',
              required: [ 'version' ],
              properties: {
                version: {
                  type: 'string'
                }
              }
            },
            meta: {
              type: 'object'
            },
            links: {
              type: 'object',
              required: [ 'self' ],
              properties: {
                self: {
                  type: 'string'
                },
                first: {
                  type: 'string'
                },
                last: {
                  type: 'string'
                },
                next: {
                  type: 'string'
                },
                prev: {
                  type: 'string'
                }
              }
            }
          }
        }
      },
      default: {
        description: 'Unexpected error',
        schema: {
          '$ref': '#/definitions/error'
        }
      }
    }
  }
  if (options.extraTags) {
    pathDefinition.tags = pathDefinition.tags.concat(options.extraTags)
    pathDefinition.tags = _.uniq(pathDefinition.tags)
  }
 
  const responseShortcut = pathDefinition.responses['200'].schema.properties
  responseShortcut.data = {
    '$ref': `#/definitions/${options.resourceName}`
  }
 
  if (options.handler === 'search') {
    responseShortcut.data = {
      type: 'array',
      items: responseShortcut.data
    }
  }
  if (((options.handler === 'search') || (options.handler === 'find')) && !options.relation) {
    pathDefinition.parameters = pathDefinition.parameters.concat(swaggerPaths._optionalJsonApiParameters())
    responseShortcut.included = {
      type: 'array',
      items: {
        type: 'object'
      }
    }
  }
 
  if ((options.handler === 'create') || (options.handler === 'update')) {
    const body = swaggerPaths._getBaseResourceModel(options.resourceName)
    if (options.relationType) {
      body.schema.properties.data = swaggerPaths._getRelationModel()
      if ((options.handler === 'update') && (options.relationType === 'many')) {
        body.schema.properties.data = {
          type: 'array',
          items: body.schema.properties.data
        }
      }
    }
    pathDefinition.parameters = pathDefinition.parameters.concat(body)
  }
 
  if (options.handler === 'delete' && options.relationType) {
    const body2 = swaggerPaths._getBaseResourceModel(options.resourceName)
    body2.schema.properties.data = swaggerPaths._getRelationModel()
    pathDefinition.parameters = pathDefinition.parameters.concat(body2)
  }
 
  if (options.handler === 'delete') {
    responseShortcut.data = undefined
  }
 
  if (options.handler === 'create') {
    pathDefinition.responses['201'] = pathDefinition.responses['200']
    pathDefinition.responses['200'] = undefined
  }
 
  if (options.hasPathId) {
    pathDefinition.parameters.push({
      name: 'id',
      in: 'path',
      description: 'id of specific instance to lookup',
      required: true,
      type: 'string'
    })
  }
 
  if (options.parameters) {
    const additionalParams = Object.keys(options.parameters).map(paramName => {
      const joiScheme = options.parameters[paramName]
      if ((paramName === 'id') || (paramName === 'type')) return null
 
      return {
        name: paramName,
        in: 'query',
        description: joiScheme._description || undefined,
        required: ((joiScheme._flags || { }).presence === 'required'),
        type: joiScheme._type
      }
    })
    pathDefinition.parameters.concat(additionalParams)
  }
 
  if (options.relationType) {
    responseShortcut.data = swaggerPaths._getRelationModel()
    if (options.relationType === 'many') {
      responseShortcut.data = {
        type: 'array',
        items: responseShortcut.data
      }
    }
  }
 
  return pathDefinition
}
 
swaggerPaths._optionalJsonApiParameters = () => [
  { '$ref': '#/parameters/sort' },
  { '$ref': '#/parameters/include' },
  { '$ref': '#/parameters/filter' },
  { '$ref': '#/parameters/fields' },
  { '$ref': '#/parameters/page' }
]
 
swaggerPaths._getRelationModel = () => ({
  type: 'object',
  required: [ 'type', 'id' ],
 
  properties: {
    type: {
      type: 'string'
    },
    id: {
      type: 'string'
    },
    meta: {
      type: 'object'
    }
  }
})
 
swaggerPaths._getBaseResourceModel = resourceName => ({
  in: 'body',
  name: 'body',
  description: 'New or partial resource',
  required: true,
 
  schema: {
    type: 'object',
    properties: {
      data: {
        '$ref': `#/definitions/${resourceName}`
      }
    }
  }
})