UNPKG

kinto-node-test-server

Version:

A node API for operating a Kinto test server.

75 lines (74 loc) 2.69 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const DEFAULT_OPTIONS = { maxAttempts: 50 }; class KintoServer { constructor(url, options = {}) { this.url = url; this.http_api_version = null; this.options = { ...DEFAULT_OPTIONS, ...options }; } async _retryRequest(url, options, attempt = 1) { const { maxAttempts } = this.options; try { const res = await fetch(url, options); if ([200, 202, 410].indexOf(res.status) === -1) { throw new Error("Unable to start server, HTTP " + res.status); } return res; } catch (err) { if (maxAttempts && attempt < maxAttempts) { return new Promise((resolve) => { setTimeout(() => { resolve(this._retryRequest(url, options, attempt + 1)); }, 100); }); } throw new Error(`Max attempts number reached (${maxAttempts}); ${err}`); } } async loadConfig(pathToConfig) { const endpoint = `${this.url}/config`; await this._retryRequest(endpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pathToConfig }), }, 1); } async start(env) { const endpoint = `${this.url}/start`; await this._retryRequest(endpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(env), }, 1); return this.ping(); } async ping() { const endpoint = `${this.url}/ping`; const res = await this._retryRequest(endpoint, {}, 1); const json = await res.json(); this.http_api_version = json.http_api_version; return this.http_api_version; } async flush() { const endpoint = `${this.url}/flush`; const res = await this._retryRequest(endpoint, { method: "POST" }, 1); return { status: res.status }; } async stop() { const endpoint = `${this.url}/stop`; await this._retryRequest(endpoint, { method: "POST" }, 1); } async killAll() { const endpoint = `${this.url}/killAll`; await this._retryRequest(endpoint, { method: "POST" }, 1); } async logs() { const endpoint = `${this.url}/logs`; const res = await this._retryRequest(endpoint, {}, 1); const json = await res.json(); return json.logs; } } exports.default = KintoServer;