All files / resources measurements.ts

95.38% Statements 62/65
83.33% Branches 5/6
100% Functions 3/3
95.38% Lines 62/65

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 661x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x       2x 2x 2x 2x 1x 1x 1x  
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import {
  Measurement,
  MeasurementsApi,
  Configuration as APIConfiguration,
} from '../codegen';
import { BaseResource } from './base';
 
dayjs.extend(utc);
 
interface MeasurementInput extends Omit<Measurement, 'time'> {
  time?: Date | string;
}
 
/**
 * We want to be flexible about the input types we accept, but we also want to
 * hit our API with a consistent response. This function takes this SDK's
 * accepted inputs for measurements and normalizes them into the Measurement
 * type.
 */
function normalizeMeasurementInput({
  time,
  ...rest
}: MeasurementInput | Measurement): Measurement {
  let timestamp: Date | undefined;
  if (time) {
    timestamp = time instanceof Date ? time : dayjs(time).utc(true).toDate();
  }
  return {
    time: timestamp,
    ...rest,
  };
}
 
class Measurements extends BaseResource {
  private api: MeasurementsApi;
 
  constructor(apiConfig: APIConfiguration) {
    super(apiConfig);
    this.api = new MeasurementsApi(apiConfig);
  }
 
  /**
   * Send Measurement (one or multiple).
   */
  public create(body: Measurement): Promise<Measurement>;
  public create(body: Measurement[]): Promise<Measurement[]>;
  public create(body: MeasurementInput): Promise<Measurement>;
  public create(body: MeasurementInput[]): Promise<Measurement[]>;
  public create(
    body: MeasurementInput | MeasurementInput[],
    overrides?: RequestInit,
  ): Promise<Measurement | Measurement[]> {
    if (Array.isArray(body)) {
      const measurement = body.map(normalizeMeasurementInput);
      return this.api.measurementsMultiPost({ measurement }, overrides);
    }
 
    const measurement = normalizeMeasurementInput(body);
    return this.api.measurementsPost({ measurement }, overrides);
  }
}
 
export { Measurements };