All files / src Petstore.ts

93.33% Statements 14/15
100% Branches 6/6
100% Functions 2/2
93.33% Lines 14/15

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                        48x           47x   46x 6x   6x 1x     5x   5x 5x   1x 1x                   40x 29x     11x      
import { Transport } from './transports/Transport.js';
import { HttpClientException } from './exceptions/HttpClientException.js';
import { PetStoreRequests } from './requests/PetstoreRequest.js';
import { HttpServerException } from './exceptions/HttpServerException.js';
import { z, ZodError } from 'zod';
import { Pet } from './responses/Pet.js';
import { UnexpectedResponseFormatException } from './exceptions/UnexpectedResponseFormatException.js';
import { UnsupportedContentTypeException } from './exceptions/UnsupportedContentTypeException.js';
 
type PetstoreResponses = Pet | Pet[];
 
export class Petstore {
  constructor(public transport: Transport) {}
 
  async send<T extends z.ZodType<PetstoreResponses>>(
    request: PetStoreRequests,
    expectedSchema: T,
  ): Promise<z.infer<T>> {
    const response = await this.transport.execute(request);
 
    if (response.ok) {
      const contentType = response.headers.get('content-type');
 
      if (contentType !== 'application/json') {
        throw new UnsupportedContentTypeException(contentType);
      }
 
      const data = await response.json();
 
      try {
        return await expectedSchema.parseAsync(data);
      } catch (zodError) {
        if (zodError instanceof ZodError) {
          throw new UnexpectedResponseFormatException(
            request,
            zodError.message,
          );
        }
 
        throw zodError;
      }
    }
 
    if (response.status >= 400 && response.status < 500) {
      throw new HttpClientException(response.status, response.statusText);
    }
 
    throw new HttpServerException(response.status, response.statusText);
  }
}