All files / src serverApiClient.ts

85.07% Statements 57/67
61.9% Branches 26/42
100% Functions 6/6
85.07% Lines 57/67

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 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 3258x 8x                 8x 8x                               8x                 8x               6x       6x 6x 6x 6x                                                     9x         9x       9x   9x         9x   8x 3x     5x   2x     3x                                                                               8x       8x         8x       8x   8x           8x 1x     7x   6x   1x     1x     3x     1x                                                               8x         8x       8x   8x         8x 1x     7x   6x   1x     3x     1x     1x                                                                             10x         10x     10x   10x         10x   9x 6x     3x   1x     2x               35x      
import { getDeleteVisitorDataUrl, getEventUrl, getVisitorsUrl } from './urlUtils'
import {
  AuthenticationMode,
  EventResponse,
  EventUpdateRequest,
  Options,
  Region,
  VisitorHistoryFilter,
  VisitorsResponse,
} from './types'
import { copyResponseJson } from './responseUtils'
import {
  ApiError,
  CommonError429,
  DeleteVisit400Error,
  DeleteVisit403Error,
  DeleteVisit404Error,
  EventError403,
  EventError404,
  UpdateEventError400,
  UpdateEventError403,
  UpdateEventError404,
  UpdateEventError409,
  VisitorsError403,
  VisitorsError429,
} from './errors/apiErrors'
 
export class FingerprintJsServerApiClient {
  public readonly region: Region
 
  public readonly apiKey: string
 
  public readonly authenticationMode: AuthenticationMode
 
  protected readonly fetch: typeof fetch
 
  protected static readonly DEFAULT_RETRY_AFTER = 1
 
  /**
   * FingerprintJS server API client used to fetch data from FingerprintJS
   * @constructor
   * @param {Options} options - Options for FingerprintJS server API client
   */
  constructor(options: Readonly<Options>) {
    Iif (!options.apiKey) {
      throw Error('Api key is not set')
    }
 
    this.region = options.region ?? Region.Global
    this.apiKey = options.apiKey
    this.authenticationMode = options.authenticationMode ?? AuthenticationMode.AuthHeader // Default auth mode is AuthHeader
    this.fetch = options.fetch ?? fetch
  }
 
  /**
   * Retrieves a specific identification event with the information from each activated product — Identification and all active [Smart signals](https://dev.fingerprint.com/docs/smart-signals-overview).
   *
   * @param requestId - identifier of the event
   *
   * @returns {Promise<EventResponse>} - promise with event response. For more information, see the [Server API documentation](https://dev.fingerprint.com/reference/getevent).
   *
   * @example
   * ```javascript
   * client
   *  .getEvent('<requestId>')
   *  .then((result) => console.log(result))
   *  .catch((err) => {
   *    if (isEventError(err)) {
   *      // You can also access the raw response
   *      console.log(err.response)
   *      console.log(`error ${err.statusCode}: `, err.message)
   *    } else {
   *      console.log('unknown error: ', err)
   *    }
   *  })
   * ```
   * */
  public async getEvent(requestId: string): Promise<EventResponse> {
    Iif (!requestId) {
      throw new TypeError('requestId is not set')
    }
 
    const url =
      this.authenticationMode === AuthenticationMode.QueryParameter
        ? getEventUrl(requestId, this.region, this.apiKey)
        : getEventUrl(requestId, this.region)
 
    const headers = this.getHeaders()
 
    const response = await this.fetch(url, {
      method: 'GET',
      headers,
    })
 
    const jsonResponse = await copyResponseJson(response)
 
    if (response.status === 200) {
      return jsonResponse as EventResponse
    }
 
    switch (response.status) {
      case 403:
        throw new EventError403(jsonResponse, response)
 
      case 404:
        throw new EventError404(jsonResponse, response)
 
      default:
        throw ApiError.unknown(response)
    }
  }
 
  /**
   * Update an event with a given request ID
   * @description Change information in existing events specified by `requestId` or *flag suspicious events*.
   *
   * When an event is created, it is assigned `linkedId` and `tag` submitted through the JS agent parameters. This information might not be available on the client so the Server API allows for updating the attributes after the fact.
   *
   * **Warning** It's not possible to update events older than 10 days.
   *
   * @param body - Data to update the event with.
   * @param requestId The unique event [identifier](https://dev.fingerprint.com/docs/js-agent#requestid).
   *
   * @return {Promise<void>}
   *
   * @example
   * ```javascript
   * const body = {
   *  linkedId: 'linked_id',
   *  suspect: false,
   * }
   *
   * client
   *   .updateEvent(body, '<requestId>')
   *   .then(() => {
   *     // Event was successfully updated
   *   })
   *   .catch((error) => {
   *     if (isUpdateEventError(error)) {
   *       console.log(error.statusCode, error.message)
   *     }
   *   })
   * ```
   */
  public async updateEvent(body: EventUpdateRequest, requestId: string): Promise<void> {
    Iif (!body) {
      throw new TypeError('body is not set')
    }
 
    Iif (!requestId) {
      throw new TypeError('requestId is not set')
    }
 
    const url =
      this.authenticationMode === AuthenticationMode.QueryParameter
        ? getEventUrl(requestId, this.region, this.apiKey)
        : getEventUrl(requestId, this.region)
 
    const headers = this.getHeaders()
 
    const response = await this.fetch(url, {
      method: 'PUT',
      headers,
      body: JSON.stringify(body),
    })
 
    if (response.status === 200) {
      return
    }
 
    const jsonResponse = await copyResponseJson(response)
 
    switch (response.status) {
      case 400:
        throw new UpdateEventError400(jsonResponse, response)
 
      case 403:
        throw new UpdateEventError403(jsonResponse, response)
 
      case 404:
        throw new UpdateEventError404(jsonResponse, response)
 
      case 409:
        throw new UpdateEventError409(jsonResponse, response)
 
      default:
        throw ApiError.unknown(response)
    }
  }
 
  /**
   * Delete data by visitor ID
   * Request deleting all data associated with the specified visitor ID. This API is useful for compliance with privacy regulations. All delete requests are queued:
   * Recent data (10 days or newer) belonging to the specified visitor will be deleted within 24 hours. * Data from older (11 days or more) identification events  will be deleted after 90 days.
   * If you are interested in using this API, please [contact our support team](https://fingerprint.com/support/) to activate it for you. Otherwise, you will receive a 403.
   *
   * @param visitorId The [visitor ID](https://dev.fingerprint.com/docs/js-agent#visitorid) you want to delete.*
   *
   * @return {Promise<void>} Promise that resolves when the deletion request is successfully queued
   *
   * @example
   * ```javascript
   * client
   *   .deleteVisitorData('<visitorId>')
   *   .then(() => {
   *     // Data deletion request was successfully queued
   *   })
   *   .catch((error) => {
   *     if (isDeleteVisitorError(error)) {
   *       console.log(error.statusCode, error.message)
   *     }
   *   })
   * ```
   */
  public async deleteVisitorData(visitorId: string): Promise<void> {
    Iif (!visitorId) {
      throw TypeError('VisitorId is not set')
    }
 
    const url =
      this.authenticationMode === AuthenticationMode.QueryParameter
        ? getDeleteVisitorDataUrl(this.region, visitorId, this.apiKey)
        : getDeleteVisitorDataUrl(this.region, visitorId)
 
    const headers = this.getHeaders()
 
    const response = await this.fetch(url, {
      method: 'DELETE',
      headers,
    })
 
    if (response.status === 200) {
      return
    }
 
    const jsonResponse = await copyResponseJson(response)
 
    switch (response.status) {
      case 429:
        throw new CommonError429(jsonResponse, response)
 
      case 404:
        throw new DeleteVisit404Error(jsonResponse, response)
 
      case 403:
        throw new DeleteVisit403Error(jsonResponse, response)
 
      case 400:
        throw new DeleteVisit400Error(jsonResponse, response)
 
      default:
        throw ApiError.unknown(response)
    }
  }
 
  /**
   * Retrieves event history for the specific visitor using the given filter, returns a promise with visitor history response.
   *
   * @param {string} visitorId - Identifier of the visitor
   * @param {VisitorHistoryFilter} filter - Visitor history filter
   * @param {string} filter.limit - limit scanned results
   * @param {string} filter.request_id - filter visits by `requestId`.
   * @param {string} filter.linked_id - filter visits by your custom identifier.
   * @param {string} filter.paginationKey - use `paginationKey` to get the next page of results.   When more results are available (e.g., you requested 200 results using `limit` parameter, but a total of 600 results are available), the `paginationKey` top-level attribute is added to the response. The key corresponds to the `requestId` of the last returned event. In the following request, use that value in the `paginationKey` parameter to get the next page of results:
   *
   *   1. First request, returning most recent 200 events: `GET api-base-url/visitors/:visitorId?limit=200`
   *   2. Use `response.paginationKey` to get the next page of results: `GET api-base-url/visitors/:visitorId?limit=200&paginationKey=1683900801733.Ogvu1j`
   *
   *   Pagination happens during scanning and before filtering, so you can get less visits than the `limit` you specified with more available on the next page. When there are no more results available for scanning, the `paginationKey` attribute is not returned.
   * @example
   * ```javascript
   * client
   *   .getVisitorHistory('<visitorId>', { limit: 1 })
   *   .then((visitorHistory) => {
   *     console.log(visitorHistory)
   *   })
   *   .catch((error) => {
   *     if (isVisitorsError(error)) {
   *       console.log(error.statusCode, error.message)
   *       if (error.status === 429) {
   *         retryLater(error.retryAfter) // Needs to be implemented on your side
   *       }
   *     }
   *   })
   * ```
   */
  public async getVisitorHistory(visitorId: string, filter?: VisitorHistoryFilter): Promise<VisitorsResponse> {
    Iif (!visitorId) {
      throw TypeError('VisitorId is not set')
    }
 
    const url =
      this.authenticationMode === AuthenticationMode.QueryParameter
        ? getVisitorsUrl(this.region, visitorId, filter, this.apiKey)
        : getVisitorsUrl(this.region, visitorId, filter)
    const headers = this.getHeaders()
 
    const response = await this.fetch(url, {
      method: 'GET',
      headers,
    })
 
    const jsonResponse = await copyResponseJson(response)
 
    if (response.status === 200) {
      return jsonResponse as VisitorsResponse
    }
 
    switch (response.status) {
      case 403:
        throw new VisitorsError403(jsonResponse, response)
 
      case 429:
        throw new VisitorsError429(jsonResponse, response)
 
      default:
        throw ApiError.unknown(response)
    }
  }
 
  private getHeaders() {
    return this.authenticationMode === AuthenticationMode.AuthHeader ? { 'Auth-API-Key': this.apiKey } : undefined
  }
}