How to use isBinaryResponse method in mountebank

Best JavaScript code snippet using mountebank

ApiHandler.ts

Source:ApiHandler.ts Github

copy

Full Screen

1import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';2import { LogicError } from '@/modules/errors/LogicError';3import { ApiError } from '@/modules/errors/ApiError';4import { RouteLocationRaw } from 'vue-router';5/**6 * Описывает объект, полученный в результате запроса с ошибкой7 */8export type ErrorResponse = {9 /**10 * Сообщение с результатом запроса11 */12 message: string13 /**14 * Массив с ошибками15 */16 errors: string[][]17 /**18 * Код ошибки19 */20 code: string21};22/**23 * Описывает параметры гет запроса24 */25export interface JsonParams {26 [param: string]: string | number | boolean | null | string[] | number[] | boolean[] | File[] | JsonParams27}28export type UploadCallback = (event: ProgressEvent) => void;29/**30 * Коды ошибок, которые могут прийти с апи31 */32export enum ApiClientErrorCodes {33 NoSigners = 'nsec'34}35export type ApiHandlerOptions = {36 fallbackRoute?: RouteLocationRaw37}38/**39 * Представляет собой обработчик апи40 * T - Тип объекта полученного с сервера41 * F - Тип преобразованного объекта42 * E - Тип объекта ошибки43 */44export abstract class ApiHandler<T = unknown, F = T, E = ErrorResponse> {45 /**46 * Ошибка, полученная в результате запроса47 */48 protected error!: AxiosError<ErrorResponse>;49 /**50 * Данные об ошибке, полученные с сервера51 */52 protected errorResponse!: ErrorResponse;53 /**54 * Конфиг для запроса на апи55 */56 protected config: AxiosRequestConfig = {};57 protected isBinaryResponse = false;58 protected options: ApiHandlerOptions = {};59 protected isRepeated = false;60 /**61 * Конфигурирует гет запрос62 *63 * @param params - параметры запроса64 * @param url - путь для запроса65 * @param uploadCallback - колбэк для обработки запроса в процессе отправки данных66 */67 public buildGetConfig(68 url: string,69 params: JsonParams,70 uploadCallback: UploadCallback | null = null71 ): ApiHandler<T, F, E> {72 this.config = Object.assign(this.config, {73 method: 'get',74 url,75 params76 });77 if (uploadCallback) {78 this.config.onUploadProgress = progressEvent => uploadCallback(progressEvent);79 }80 return this;81 }82 /**83 * Конфигурирует пост запрос с форм датой84 *85 * @param url - путь для запроса86 * @param data - данные для отправки87 * @param uploadCallback - колбэк для обработки запроса в процессе отправки данных88 */89 public buildPostConfig(90 url: string,91 data: FormData,92 uploadCallback: UploadCallback | null = null93 ): ApiHandler<T, F, E> {94 this.config = Object.assign(this.config, {95 method: 'post',96 url,97 data,98 headers: {99 'Content-Type': 'multipart/form-data'100 }101 });102 if (uploadCallback) {103 this.config.onUploadProgress = progressEvent => uploadCallback(progressEvent);104 }105 return this;106 }107 constructor(options?: ApiHandlerOptions) {108 if (options) {109 this.options = options;110 }111 }112 /**113 * Конфигурирует пост запрос с json114 *115 * @param params - параметры запроса116 * @param url - путь для запроса117 * @param uploadCallback - колбэк для обработки запроса в процессе отправки данных118 */119 public buildPostJSONConfig(120 url: string,121 params: JsonParams,122 uploadCallback: UploadCallback | null = null123 ): ApiHandler<T, F, E> {124 this.config = Object.assign(this.config, {125 method: 'post',126 url,127 data: params,128 headers: {129 'Content-Type': 'application/json'130 }131 });132 if (uploadCallback) {133 this.config.onUploadProgress = progressEvent => uploadCallback(progressEvent);134 }135 return this;136 }137 /**138 * Конфигурирует гет запрос для получения бинарных данных139 *140 * @param url - путь для запроса141 * @param uploadCallback - колбэк для обработки запроса в процессе отправки данных142 */143 public buildGetBinaryDataConfig(144 url: string,145 uploadCallback: UploadCallback | null = null146 ): ApiHandler<T, F, E> {147 this.config = Object.assign(this.config, {148 method: 'get',149 url,150 responseType: 'arraybuffer'151 });152 if (uploadCallback) {153 this.config.onUploadProgress = progressEvent => uploadCallback(progressEvent);154 }155 this.isBinaryResponse = true;156 return this;157 }158 /**159 * Устанавливает время ожидания ответа для запроса160 */161 public setTimeout(milliseconds: number): ApiHandler<T, F, E> {162 this.config.timeout = milliseconds;163 return this;164 }165 private async handleResponse(response: AxiosResponse) {166 if (this.isValidSuccessResponse(response)) {167 const apiData = this.isBinaryResponse ? response.data : response.data.data;168 // Для теста169 // if (this.config.url === '/api/signatureSessions/navigation/items/waitingAction') {170 // }171 return Promise.resolve(this.handleSuccessResponse(apiData));172 } else if (response.status === 204) {173 return Promise.reject(response);174 } else {175 // console.error(response);176 // reject(response);177 throw new ApiError(178 'Ошибка при выполнении запроса',179 'Не ожидалось ответа с таким статусом',180 new Error()181 );182 // return Promise.reject(response);183 }184 }185 private async handleReject(error: AxiosError<ErrorResponse>) {186 this.error = error as AxiosError<ErrorResponse>;187 if (this.isValidErrorResponse(error)) {188 this.errorResponse = this.error.response!.data;189 if (this.error.response?.status.toString().startsWith('4')) {190 return Promise.reject(this.clientFatalError());191 } else {192 return Promise.reject(this.serverFatalError());193 }194 } else if (error.response) {195 if (error.response.status === 500) {196 return Promise.reject(this.serverFatalError());197 } else {198 throw new ApiError('Непредвиденная ошибка при выполнении запроса', 'Обратитесь к администратору', error);199 }200 } else if (error.request) {201 throw new ApiError('Не получен ответ от сервера', 'Обратитесь к администратору', error);202 } else {203 throw new ApiError('Непредвиденная ошибка при выполнении запроса', 'Обратитесь к администратору', error);204 }205 }206 /**207 * Отправляет и обрабатывает запрос на api208 *209 * @returns Промис с данными полученными с api210 */211 public async send(): Promise<F> {212 if (!this.config.method || !this.config.url) {213 throw new LogicError('Отсутствует конфиг запроса');214 }215 // return new Promise<F>((resolve, reject) => {216 // console.log('request');217 return axios.request(this.config)218 .then((response: AxiosResponse) => {219 return this.handleResponse(response);220 })221 .catch((error: AxiosError<ErrorResponse>) => {222 return this.handleReject(error);223 });224 }225 /**226 * Проверяет содержит ли успешный ответ с api ожидаемые данные227 *228 * @param response - ответ с api229 */230 private isValidSuccessResponse(response: AxiosResponse): boolean {231 return (232 response.status === 200 &&233 (this.isValidJSONResponse(response) || this.isBinaryResponse)234 );235 }236 private isValidJSONResponse(response: AxiosResponse): boolean {237 return (238 response.data.hasOwnProperty('message') &&239 response.data.hasOwnProperty('data')240 );241 }242 protected handleSuccessResponse(data: T): F {243 return data as unknown as F;244 }245 /**246 * Проверяет содержит ли объект ошибки с api ожидаемые данные247 *248 * @param error - ответ с api249 */250 private isValidErrorResponse(error: AxiosError): boolean {251 return (252 !!error.response &&253 !!error.response.data &&254 error.response.data.hasOwnProperty('message') &&255 error.response.data.hasOwnProperty('errors') &&256 error.response.data.hasOwnProperty('code')257 );258 }259 /**260 * Обработка клиентской ошибки запроса по умолчанию261 */262 protected clientFatalError(): E | ErrorResponse {263 const errorCode: string = this.error.response?.data.code ?? '';264 if (265 this.error.response?.status === 422 &&266 errorCode !== '' &&267 this.getHandledErrorCodes().includes(errorCode)268 ) {269 return this.clientInvalidArgumentError();270 } else {271 return this.defaultError();272 }273 }274 /**275 * Получает массив обрабатываемых ошибок для апи276 */277 protected getHandledErrorCodes(): string[] {278 return [];279 }280 /**281 * Обрабатывает случай, когда входные параметры со стороны Js невалидны.282 * Это может быть связано с ошибкой при входной валидации или ошибкой в логике283 */284 protected clientInvalidArgumentError(): E | ErrorResponse {285 return this.defaultError();286 }287 /**288 * Обработка серверной ошибки запроса по умолчанию289 */290 protected serverFatalError(): E | ErrorResponse {291 return this.defaultError();292 }293 /**294 * Вывод ошибки по умолчанию295 */296 private defaultError(): ErrorResponse {297 throw new ApiError(298 'Непредвиденная ошибка при выполнении запроса',299 'Обратитесь к администратору',300 this.error301 );302 }...

Full Screen

Full Screen

api-gateway.js

Source:api-gateway.js Github

copy

Full Screen

1/* load-hot */2import assert from 'assert';3import set from 'lodash.set';4import get from 'lodash.get';5import { wrap as lambdaAsyncWrap } from 'lambda-async';6import { logger } from 'lambda-monitor-logger';7import { serializeError } from 'serialize-error';8const getErrorMessage = (error) => String(get(error, 'message', 'Exception')).split('\n')[0];9export const asApiGatewayResponse = (resp, stringifyJson = true) => {10 if (get(resp, 'isApiResponse') !== true) {11 throw resp;12 }13 const isApiError = get(resp, 'isApiError');14 assert([true, false].includes(isApiError));15 let body = isApiError ? {16 message: resp.message,17 messageId: resp.messageId,18 context: resp.context19 } : resp.payload;20 const isJsonResponse = get(resp, 'isJsonResponse') === true;21 if (isJsonResponse && stringifyJson) {22 body = JSON.stringify(body);23 }24 const isBinaryResponse = get(resp, 'isBinaryResponse') === true;25 if (isBinaryResponse) {26 body = body.toString('base64');27 }28 return {29 statusCode: resp.statusCode,30 body,31 ...(Object.keys(resp.headers).length === 0 ? {} : { headers: resp.headers }),32 ...(isBinaryResponse ? { isBase64Encoded: true } : {})33 };34};35export const wrap = ({36 handler,37 request,38 route,39 router,40 module,41 params = []42}) => async (event, context) => {43 if (!event.httpMethod) {44 return Promise.resolve('OK - No API Gateway call detected.');45 }46 set(context, 'custom.executionStart', new Date() / 1);47 if (!('path' in event)) {48 Object.assign(event, {49 path: request.route50 .replace(/^[^\s]+ \/?/, '/')51 .replace(/{([^}]+?)\+?}/g, (_, e) => get(event, ['pathParameters', e]))52 });53 }54 const kwargs = {55 request,56 event,57 context,58 route,59 router,60 params61 };62 let isError = false;63 const apply = [64 async () => {65 const resp = await module.before(kwargs);66 assert(resp === null, 'Plugin before() should not return');67 return handler(context.parsedParameters, context, event);68 },69 async (prevResp) => {70 if (!isError) {71 const resp = await module.afterSuccess(kwargs);72 assert(resp === null, 'Plugin afterSuccess() should not return');73 }74 return prevResp;75 },76 async (prevResp) => {77 const resp = await module.after(kwargs);78 assert(resp === null, 'Plugin after() should not return');79 return prevResp;80 }81 ];82 for (let idx = 0; idx < apply.length; idx += 1) {83 try {84 // eslint-disable-next-line no-await-in-loop85 kwargs.response = await apply[idx](kwargs.response);86 } catch (err) {87 assert(idx === 0, 'Should not throw from afterSuccess() or after()');88 kwargs.response = err;89 isError = true;90 }91 assert(get(kwargs, 'response.isApiError', true) === isError);92 if (get(kwargs, 'response.isApiResponse', false) !== true) {93 break;94 }95 }96 return asApiGatewayResponse(kwargs.response);97};98export const wrapAsync = (handler) => {99 const h = (...kwargs) => handler(...kwargs).catch((error) => {100 logger.warn([101 `${getErrorMessage(error)}: ${handler.route}`,102 JSON.stringify({103 context: 'lambda-serverless-api',104 route: handler.route,105 error: serializeError(error)106 })107 ].join('\n'));108 return {109 statusCode: 500,110 body: '{"message":"Internal Server Error"}'111 };112 });113 return Object.assign(114 lambdaAsyncWrap(h),115 Object116 .entries(handler)117 .reduce((p, [k, v]) => Object.assign(p, { [k]: v }), {})118 );...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const path = require('path')2const got = require('got')3class OpenFaaS {4 constructor(gateway) {5 this.gateway = gateway6 }7 list() {8 const funcsPath = '/system/functions'9 const options = {10 json: true11 }12 return got(this.gateway + funcsPath, options)13 }14 invoke(func, data, { isJson = false, isBinaryResponse = false } = {}) {15 const funcPath = path.join('/function', func)16 const options = {17 method: 'POST',18 json: isJson,19 encoding: (isBinaryResponse ? null : 'utf8')20 }21 if (data) {22 options.body = data23 }24 return got(this.gateway + funcPath, options)25 }26 inspect(func) {27 return new Promise((resolve, reject) => {28 return this.list()29 .then(res => {30 const funcs = res.body31 for (let i = 0; i < funcs.length; i++) {32 if (funcs[i].name === func) {33 return resolve({ body: funcs[i], statusCode: res.statusCode })34 }35 }36 resolve()37 }).catch(reject)38 })39 }40 deploy(func, image, { network = 'func_functions' } = {}) {41 const deployPath = path.join('/system/functions')42 const options = {43 method: 'POST',44 json: true,45 body: {46 service: func,47 image,48 network49 }50 }51 return got(this.gateway + deployPath, options)52 }53 remove(name) {54 const options = {55 method: 'DELETE',56 json: true,57 body: {58 functionName: name59 }60 }61 return got(this.gateway + '/system/functions', options)62 }63 compose(initial, funcs) {64 const functions = funcs.map(func => {65 return data => {66 const options = {67 method: 'POST',68 body: data69 }70 const funcUrl = this.gateway + path.join('/function', func)71 return got(funcUrl, options)72 .then(res => Promise.resolve(res))73 .catch(err => Promise.reject(err))74 }75 })76 return functions.reduce(77 (current, f) => {78 return current.then(x => f(x.body))79 },80 new Promise(resolve => resolve(initial))81 )82 }83}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var isBinaryResponse = mb.isBinaryResponse;3var fs = require('fs');4var imposter = {5 {6 {7 is: {8 headers: {9 },10 body: fs.readFileSync('logo.png')11 }12 }13 }14};15mb.create(imposter).then(function (result) {16 console.log(result);17 return mb.get('/imposters/' + result.port, {replayable: true});18}).then(function (imposter) {19 console.log(isBinaryResponse(imposter.stubs[0].responses[0]));20});

Full Screen

Using AI Code Generation

copy

Full Screen

1const isBinaryResponse = require('mountebank').isBinaryResponse;2if (isBinaryResponse(response)) {3 console.log('Response is binary');4} else {5 console.log('Response is not binary');6}7const isBinaryResponse = require('mountebank').isBinaryResponse;8if (isBinaryResponse(response)) {9 console.log('Response is binary');10} else {11 console.log('Response is not binary');12}13const isBinaryResponse = require('mountebank').isBinaryResponse;14if (isBinaryResponse(response)) {15 console.log('Response is binary');16} else {17 console.log('Response is not binary');18}19const isBinaryResponse = require('mountebank').isBinaryResponse;20if (isBinaryResponse(response)) {21 console.log('Response is binary');22} else {23 console.log('Response is not binary');24}25const isBinaryResponse = require('mountebank').isBinaryResponse;26if (isBinaryResponse(response)) {27 console.log('Response is binary');28} else {29 console.log('Response is not binary');30}31const isBinaryResponse = require('mountebank').isBinaryResponse;32if (isBinaryResponse(response)) {33 console.log('Response is binary');34} else {35 console.log('Response is not binary');36}37const isBinaryResponse = require('mountebank').isBinaryResponse;38if (isBinaryResponse(response)) {39 console.log('Response is binary');40} else {41 console.log('Response is not binary');42}43const isBinaryResponse = require('mountebank').isBinaryResponse;

Full Screen

Using AI Code Generation

copy

Full Screen

1var imposter = {2 stubs: [{3 responses: [{4 is: {5 }6 }]7 }]8};9var mb = require('mountebank'),10 assert = require('assert'),11 Q = require('q');12mb.start({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log' })13 .then(function () {14 return mb.post('/imposters', imposter);15 })16 .then(function (response) {17 assert.equal(response.statusCode, 201);18 return mb.get('/imposters/8000');19 })20 .then(function (response) {21 assert.equal(response.statusCode, 200);22 assert.equal(response.body.stubs[0].responses[0].is.body, 'foo');23 return mb.del('/imposters/8000');24 })25 .then(function (response) {26 assert.equal(response.statusCode, 200);27 return mb.del('/imposters');28 })29 .then(function (response) {30 assert.equal(response.statusCode, 200);31 return mb.stop();32 })33 .then(function () {34 console.log('All done!');35 })36 .done();37var imposter = {38 stubs: [{39 responses: [{40 is: {41 }42 }]43 }]44};45var mb = require('mountebank'),46 assert = require('assert'),47 Q = require('q');48mb.start({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log' })49 .then(function () {50 return mb.post('/imposters', imposter);51 })52 .then(function (response) {53 assert.equal(response.statusCode, 201);54 return mb.get('/imposters/8000');55 })56 .then(function (response) {57 assert.equal(response.statusCode, 200);58 assert.equal(response.body.stubs[0].responses[0].is.body, 'foo');59 return mb.del('/imposters/8000');60 })61 .then(function (response) {62 assert.equal(response.statusCode, 200);63 return mb.del('/impost

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var isBinaryResponse = mb.isBinaryResponse;3var response = { body: 'hello world' };4response = { binary: 'hello world' };5var mb = require('mountebank');6var isBinaryResponse = mb.isBinaryResponse;7var imposter = {8 {9 {10 is: {11 },12 _behaviors: {13 }14 },15 {16 is: {17 },18 _behaviors: {19 }20 }21 }22};23var imposterResponse = mb.create(imposter);24console.log(imposterResponse);25var stubs = imposterResponse.stubs;26for (var i = 0; i < stubs.length; i++) {27 var stub = stubs[i];28 var responses = stub.responses;29 for (var j = 0; j < responses.length; j++) {30 var response = responses[j];31 if (isBinaryResponse(response)) {32 response.binary = true;33 }34 }35}36var updateResponse = mb.update(imposterResponse.port, imposterResponse);37console.log(updateResponse);

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var isBinaryResponse = mb.isBinaryResponse;3var response = {4headers: {5},6};7console.log(isBinaryResponse(response));8var mb = require('mountebank');9var isBinaryResponse = mb.isBinaryResponse;10var response = {11headers: {12},13body: {14}15};16console.log(isBinaryResponse(response));17var mb = require('mountebank');18var isBinaryResponse = mb.isBinaryResponse;19var response = {20headers: {21},22};23console.log(isBinaryResponse(response));24var mb = require('mountebank');25var isBinaryResponse = mb.isBinaryResponse;26var response = {27headers: {28},29body: {30}31};32console.log(isBinaryResponse(response));33var mb = require('mountebank');34var isBinaryResponse = mb.isBinaryResponse;35var response = {36headers: {37},38body: {39}40};41console.log(isBinaryResponse(response));42var mb = require('mountebank');43var isBinaryResponse = mb.isBinaryResponse;44var response = {45headers: {46},47body: {48}49};50console.log(isBinaryResponse(response));51var mb = require('mountebank');52var isBinaryResponse = mb.isBinaryResponse;53var response = {54headers: {55},

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank-client');2const options = { port: 2525, protocol: 'http' };3const client = mb.create(options);4client.isBinaryResponse('localhost', 3000, '/test', 'GET', 'test', 'text/plain').then(response => {5 console.log(response);6});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run mountebank automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful