All files / utils/api normalizeResults.ts

99.05% Statements 209/211
89.47% Branches 34/38
100% Functions 1/1
99.05% Lines 209/211

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 2121x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 1x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 3304x 616x 616x 112x 112x 112x 112x 112x 112x 112x 105x 1365x 105x 105x 1365x 1365x 1365x 1155x 945x 945x 945x 945x 945x 1155x 1155x 1155x 19x 1155x 18x 18x 18x 18x 18x 18x 18x 18x 18x 61x 28x 28x 18x 18x 18x 18x 1155x 1365x 1365x 1365x 210x 210x 210x 210x 210x 210x 210x 210x 93x 1230x 1230x 1230x 1230x 1230x 1230x 1230x 1230x 6405x 255x 255x 1230x 1230x 1230x 1230x 1230x 93x 210x 210x 210x 210x 210x 210x 210x 93x 93x 210x 105x 105x 112x 112x 112x 112x 112x 5x 5x 5x     5x  
import { CustomError } from '../error'
 
type TLinks = {
  self: string
  first?: object
  last?: object
  next?: object
  prev?: object
}
 
type TResponse = {
  links: TLinks
  data: TDataElement[]
  metadata: {
    total: number
    page: number
    pages: number
    size: number
  }
}
 
type TDataElement = {
  type: string
  id: string
  links: TLinks
  attributes: {
    [key: string]: any
  }
  relationships?: {
    [key: string]: any
  }
}
 
export default (req) => {
  try {
    const { queryResult, settings } = req
    const { url, responseType } = settings
    const entity = req.params.children ?? req.params.entity
    if (responseType === 'json') return queryResult.primary
 
    const { entityDef, body } = req
    const { primaryKey } = entityDef
    const result: TResponse = {
      links: {
        self: url,
        first: {
          url,
          body: {
            ...body,
            pagination: {
              ...body.pagination,
              page: 1,
            },
          },
        },
        last: {
          url,
          body: {
            ...body,
            pagination: {
              ...body.pagination,
              page: queryResult.metadata.pages,
            },
          },
        },
      },
      data: [],
      metadata: queryResult.metadata,
    }
    if (result.metadata.page < result.metadata.pages) {
      result.links.next = {
        url,
        body: {
          ...body,
          pagination: {
            ...body.pagination,
            page: result.metadata.page + 1,
          },
        },
      }
    }
    if (
      result.metadata.page > 1 &&
      result.metadata.page <= result.metadata.pages
    ) {
      result.links.prev = {
        url,
        body: {
          ...body,
          pagination: {
            ...body.pagination,
            page: result.metadata.page - 1,
          },
        },
      }
    }
 
    let fields = body.fields && body.fields[entity] ? body.fields[entity] : []
    fields = fields.map((field) => field.trim())
 
    for (const record of queryResult.primary) {
      const element: TDataElement = {
        type: entity,
        id: record[primaryKey],
        links: {
          self: `${url}/${record[primaryKey]}`,
        },
        attributes: {},
      }
 
      /**
       * Attributes handler
       */
      Object.keys(record).forEach((key) => {
        if (!fields.length || fields.includes(key)) {
          element.attributes[key] = record[key]
        }
      })
      /* END Attributes handler */
 
      /**
       * Relationships handler
       */
      if (entity === req.params.entity && entityDef.relationships) {
        Object.keys(entityDef.relationships).forEach((relationship) => {
          if (!element.relationships) {
            element.relationships = {}
          }
 
          // has-one
          if (entityDef.relationships[relationship].type === 'has-one') {
            if (record[entityDef.relationships[relationship].foreignKey]) {
              element.relationships[relationship] = {
                type: relationship,
                id: record[entityDef.relationships[relationship].foreignKey],
              }
            }
            // Handle included relationships
            if (
              queryResult.secondary[relationship] &&
              queryResult.secondary[relationship].length
            ) {
              let relatedFields =
                body.fields && body.fields[relationship]
                  ? body.fields[relationship]
                  : []
              relatedFields = relatedFields.map((field) => field.trim())
 
              const relatedRecord = queryResult.secondary[relationship][0]
              if (relatedFields.length) {
                Object.keys(relatedRecord).forEach((key) => {
                  if (!relatedFields.includes(key)) {
                    delete relatedRecord[key]
                  }
                })
              }
              element.relationships[relationship].attributes = relatedRecord
            }
          }
 
          // has-many
          if (entityDef.relationships[relationship].type === 'has-many') {
            let relatedFields =
              body.fields && body.fields[relationship]
                ? body.fields[relationship]
                : []
            relatedFields = relatedFields.map((field) => field.trim())
 
            const relatedRecords: Record<string, any>[] = []
            if (queryResult.secondary[relationship]) {
              for (const relatedRecord of queryResult.secondary[relationship]) {
                const record: Record<string, any> = {
                  type: relationship,
                  id: relatedRecord[
                    entityDef.relationships[relationship].primaryKey
                  ],
                }
                if (relatedFields.length) {
                  Object.keys(relatedRecord).forEach((key) => {
                    if (!relatedFields.includes(key)) {
                      delete relatedRecord[key]
                    }
                  })
                }
                record.attributes = relatedRecord
                relatedRecords.push(record)
              }
            }
 
            element.relationships[relationship] = {
              links: {
                related: `${url}/${record[primaryKey]}/${relationship}`,
              },
            }
            if (queryResult.secondary[relationship]) {
              element.relationships[relationship].data = relatedRecords || []
            }
          }
        })
      }
 
      /* END Relationships handler */
 
      result.data.push(element)
    }
 
    return result
  } catch (error: any) {
    throw new CustomError(`[normalizeDataStoreResults] ${error.message}`, 400)
  }
}