How to use _ensureProperty method in root

Best JavaScript code snippet using root

DetoxConfigErrorComposer.js

Source:DetoxConfigErrorComposer.js Github

copy

Full Screen

...78 const config = this._getSelectedConfiguration();79 return config.type ? config : config.device;80 }81 }82 _ensureProperty(...names) {83 return obj => {84 for (const name of names) {85 return _.set(obj, name, _.get(obj, name));86 }87 };88 }89 // region setters90 setConfigurationName(configurationName) {91 this.configurationName = configurationName || '';92 return this;93 }94 setDetoxConfigPath(filepath) {95 this.filepath = filepath || '';96 return this;97 }98 setDetoxConfig(contents) {99 this.contents = contents || null;100 return this;101 }102 setExtends(value) {103 this._extends = !!value;104 return this;105 }106 // endregion107 // region configuration/index108 noConfigurationSpecified() {109 return new DetoxConfigError({110 message: 'Cannot run Detox without a configuration file.',111 hint: _.endsWith(this.filepath, 'package.json')112 ? `Create an external .detoxrc.json configuration, or add "detox" configuration section to your package.json at:\n${this.filepath}`113 : 'Make sure to create external .detoxrc.json configuration in the working directory before you run Detox.'114 });115 }116 noConfigurationAtGivenPath(givenPath) {117 const message = this._extends118 ? `Failed to find the base Detox config specified in:\n{\n "extends": ${J(givenPath)}\n}`119 : `Failed to find Detox config at ${J(givenPath)}`;120 const hint = this._extends121 ? `Check your Detox config${this._atPath()}`122 : 'Make sure the specified path is correct.';123 return new DetoxConfigError({ message, hint });124 }125 failedToReadConfiguration(unknownError) {126 return new DetoxConfigError({127 message: 'An error occurred while trying to load Detox config from:\n' + this.filepath,128 debugInfo: unknownError,129 });130 }131 noConfigurationsInside() {132 return new DetoxConfigError({133 message: `There are no configurations in the given Detox config${this._atPath()}`,134 hint: `Examine the config:`,135 debugInfo: this.contents ? {136 configurations: undefined,137 ...this.contents,138 } : {},139 inspectOptions: { depth: 1 },140 });141 }142 cantChooseConfiguration() {143 const configurations = this.contents.configurations;144 return new DetoxConfigError({145 message: `Cannot determine which configuration to use from Detox config${this._atPath()}`,146 hint: 'Use --configuration to choose one of the following:\n' + hintList(configurations),147 });148 }149 noConfigurationWithGivenName() {150 const configurations = this.contents.configurations;151 return new DetoxConfigError({152 message: `Failed to find a configuration named ${J(this.configurationName)} in Detox config${this._atPath()}`,153 hint: 'Below are the configurations Detox was able to find:\n' + hintList(configurations),154 });155 }156 configurationShouldNotBeEmpty() {157 const name = this.configurationName;158 const configurations = this.contents.configurations;159 return new DetoxConfigError({160 message: `Cannot use an empty configuration ${J(name)}.`,161 hint: `A valid configuration should have "device" and "app" properties defined, e.g.:\n162{163 "apps": {164*-->"myApp.ios": {165| "type": "ios.app",166| "binaryPath": "path/to/app"167| },168| },169| "devices": {170|*->"simulator": {171|| "type": "ios.simulator",172|| "device": { type: "iPhone 12" }173|| },174||},175||"configurations": {176|| ${J(name)}: {177|*--- "device": "simulator",178*---- "app": "myApp.ios"179 }180 }181}182Examine your Detox config${this._atPath()}`,183 debugInfo: {184 configurations: {185 [name]: configurations[name],186 ...configurations,187 }188 },189 inspectOptions: { depth: 1 }190 });191 }192 // endregion193 // region composeDeviceConfig194 thereAreNoDeviceConfigs(deviceAlias) {195 return new DetoxConfigError({196 message: `Cannot use device alias ${J(deviceAlias)} since there is no "devices" config in Detox config${this._atPath()}`,197 hint: `\198You should create a dictionary of device configurations in Detox config, e.g.:199{200 "devices": {201*-> ${J(deviceAlias)}: {202| "type": "ios.simulator", // or "android.emulator", or etc...203| "device": { "type": "iPhone 12" }, // or e.g.: { "avdName": "Pixel_API_29" }204| }205| },206| "configurations": {207| ${J(this.configurationName)}: {208*---- "device": ${J(deviceAlias)},209 ...210 }211 }212}\n`,213 });214 }215 cantResolveDeviceAlias(alias) {216 return new DetoxConfigError({217 message: `Failed to find a device config ${J(alias)} in the "devices" dictionary of Detox config${this._atPath()}`,218 hint: 'Below are the device configurations Detox was able to find:\n'219 + hintList(this.contents.devices) + '\n\n'220 + `Check your configuration ${J(this.configurationName)}:`,221 debugInfo: this._getSelectedConfiguration(),222 inspectOptions: { depth: 0 },223 });224 }225 deviceConfigIsUndefined() {226 return new DetoxConfigError({227 message: `Missing "device" property in the selected configuration ${J(this.configurationName)}:`,228 hint: `It should be an alias to the device config, or the device config itself, e.g.:229{230 ...231 "devices": {232*-> "myDevice": {233| "type": "ios.simulator", // or "android.emulator", or etc...234| "device": { "type": "iPhone 12" }, // or e.g.: { "avdName": "Pixel_API_29" }235| }236| },237| "configurations": {238| ${J(this.configurationName)}: {239*---- "device": "myDevice", // or { type: 'ios.simulator', ... }240 ...241 },242 ...243 }244}245Examine your Detox config${this._atPath()}`,246 });247 }248 missingDeviceType(deviceAlias) {249 return new DetoxConfigError({250 message: `Missing "type" inside the device configuration.`,251 hint: `Usually, "type" property should hold the device type to test on (e.g. "ios.simulator" or "android.emulator").\n` +252 `Check that in your Detox config${this._atPath()}`,253 debugInfo: this._focusOnDeviceConfig(deviceAlias, this._ensureProperty('type')),254 inspectOptions: { depth: 3 },255 });256 }257 invalidDeviceType(deviceAlias, deviceConfig, innerError) {258 return new DetoxConfigError({259 message: `Invalid device type ${J(deviceConfig.type)} inside your configuration.`,260 hint: `Did you mean to use one of these?261${hintList(deviceAppTypes)}262P.S. If you intended to use a third-party driver, please resolve this error:263${innerError.message}264Please check your Detox config${this._atPath()}`,265 debugInfo: this._focusOnDeviceConfig(deviceAlias, this._ensureProperty('type')),266 inspectOptions: { depth: 3 },267 });268 }269 _invalidPropertyType(propertyName, expectedType, deviceAlias) {270 return new DetoxConfigError({271 message: `Invalid type of ${J(propertyName)} inside the device configuration.\n`272 + `Expected ${expectedType}.`,273 hint: `Check that in your Detox config${this._atPath()}`,274 debugInfo: this._focusOnDeviceConfig(deviceAlias),275 inspectOptions: { depth: 3 },276 });277 }278 _unsupportedPropertyByDeviceType(propertyName, supportedDeviceTypes, deviceAlias) {279 const { type } = this._getDeviceConfig(deviceAlias);280 return new DetoxConfigError({281 message: `The current device type ${J(type)} does not support ${J(propertyName)} property.`,282 hint: `You can use this property only with the following device types:\n` +283 hintList(supportedDeviceTypes) + '\n\n' +284 `Please fix your Detox config${this._atPath()}`,285 debugInfo: this._focusOnDeviceConfig(deviceAlias),286 inspectOptions: { depth: 4 },287 });288 }289 malformedDeviceProperty(deviceAlias, propertyName) {290 switch (propertyName) {291 case 'bootArgs':292 return this._invalidPropertyType('bootArgs', 'a string', deviceAlias);293 case 'utilBinaryPaths':294 return this._invalidPropertyType('utilBinaryPaths', 'an array of strings', deviceAlias);295 case 'forceAdbInstall':296 return this._invalidPropertyType('forceAdbInstall', 'a boolean value', deviceAlias);297 case 'gpuMode':298 return this._invalidPropertyType('gpuMode', "'auto' | 'host' | 'swiftshader_indirect' | 'angle_indirect' | 'guest'", deviceAlias);299 case 'headless':300 return this._invalidPropertyType('headless', 'a boolean value', deviceAlias);301 case 'readonly':302 return this._invalidPropertyType('readonly', 'a boolean value', deviceAlias);303 default:304 throw new DetoxInternalError(`Composing .malformedDeviceProperty(${propertyName}) is not implemented`);305 }306 }307 unsupportedDeviceProperty(deviceAlias, propertyName) {308 switch (propertyName) {309 case 'bootArgs':310 return this._unsupportedPropertyByDeviceType('bootArgs', ['ios.simulator', 'android.emulator'], deviceAlias);311 case 'forceAdbInstall':312 return this._unsupportedPropertyByDeviceType('forceAdbInstall', ['android.attached', 'android.emulator', 'android.genycloud'], deviceAlias);313 case 'gpuMode':314 return this._unsupportedPropertyByDeviceType('gpuMode', ['android.emulator'], deviceAlias);315 case 'headless':316 return this._unsupportedPropertyByDeviceType('headless', ['android.emulator'], deviceAlias);317 case 'readonly':318 return this._unsupportedPropertyByDeviceType('readonly', ['android.emulator'], deviceAlias);319 case 'utilBinaryPaths':320 return this._unsupportedPropertyByDeviceType('utilBinaryPaths', ['android.attached', 'android.emulator', 'android.genycloud'], deviceAlias);321 default:322 throw new DetoxInternalError(`Composing .unsupportedDeviceProperty(${propertyName}) is not implemented`);323 }324 }325 missingDeviceMatcherProperties(deviceAlias, expectedProperties) {326 const { type } = this._resolveSelectedDeviceConfig(deviceAlias);327 return new DetoxConfigError({328 message: `Invalid or empty "device" matcher inside the device config.`,329 hint: `It should have the device query to run on, e.g.:\n330{331 "type": ${J(type)},332 "device": ${expectedProperties.map(p => `{ ${J(p)}: ... }`).join('\n // or ')}333}334Check that in your Detox config${this._atPath()}`,335 debugInfo: this._focusOnDeviceConfig(deviceAlias),336 inspectOptions: { depth: 4 },337 });338 }339 // endregion340 // region composeAppsConfig341 thereAreNoAppConfigs(appAlias) {342 return new DetoxConfigError({343 message: `Cannot use app alias ${J(appAlias)} since there is no "apps" config in Detox config${this._atPath()}`,344 hint: `\345You should create a dictionary of app configurations in Detox config, e.g.:346{347 "apps": {348*-> ${J(appAlias)}: {349| "type": "ios.app", // or "android.apk", or etc...350| "binaryPath": "path/to/your/app", // ... and so on351| }352| },353| "configurations": {354| ${J(this.configurationName)}: {355*---- "app": ${J(appAlias)},356 ...357 }358 }359}\n`,360 });361 }362 cantResolveAppAlias(appAlias) {363 return new DetoxConfigError({364 message: `Failed to find an app config ${J(appAlias)} in the "apps" dictionary of Detox config${this._atPath()}`,365 hint: 'Below are the app configurations Detox was able to find:\n' + hintList(this.contents.apps) +366 `\n\nCheck your configuration ${J(this.configurationName)}:`,367 debugInfo: this._getSelectedConfiguration(),368 inspectOptions: { depth: 1 },369 });370 }371 appConfigIsUndefined(appPath) {372 const appProperty = appPath[2] === 'apps'373 ? `"apps": [..., "myApp", ...]`374 : `"app": "myApp"`;375 return new DetoxConfigError({376 message: `Undefined or empty app config in the selected ${J(this.configurationName)} configuration:`,377 hint: `\378It should be an alias to an existing app config in "apps" dictionary, or the config object itself, e.g.:379{380 "apps": {381*-> "myApp": {382| "type": "ios.app", // or "android.apk", or etc...383| "binaryPath": "path/to/your/app", // ... and so on384| }385| },386| "configurations": {387| ${J(this.configurationName)}: {388*---- ${appProperty}389 ...390 }391 }392Examine your Detox config${this._atPath()}`,393 debugInfo: this._focusOnConfiguration(),394 inspectOptions: { depth: 2 }395 });396 }397 malformedAppLaunchArgs(appPath) {398 return new DetoxConfigError({399 message: `Invalid type of "launchArgs" property ${this._inTheAppConfig()}.\nExpected an object:`,400 debugInfo: this._focusOnAppConfig(appPath),401 inspectOptions: { depth: 4 },402 });403 }404 missingAppBinaryPath(appPath) {405 return new DetoxConfigError({406 message: `Missing "binaryPath" property ${this._inTheAppConfig()}.\nExpected a string:`,407 debugInfo: this._focusOnAppConfig(appPath, this._ensureProperty('binaryPath')),408 inspectOptions: { depth: 4 },409 });410 }411 invalidAppType({ appPath, allowedAppTypes, deviceType }) {412 return new DetoxConfigError({413 message: `Invalid app "type" property in the app config.\nExpected ${allowedAppTypes.map(J).join(' or ')}.`,414 hint: `\415You have a few options:4161. Replace the value with the suggestion.4172. Use a correct device type with this app config. Currently you have ${J(deviceType)}.`,418 debugInfo: this._focusOnAppConfig(appPath),419 inspectOptions: { depth: 4 },420 });421 }422 duplicateAppConfig({ appName, appPath, preExistingAppPath }) {423 const config1 = { ..._.get(this.contents, preExistingAppPath) };424 config1.name = config1.name || '<GIVE IT A NAME>';425 const config2 = { ..._.get(this.contents, appPath) };426 config2.name = '<GIVE IT ANOTHER NAME>';427 const name = this.configurationName;428 const hintMessage = appName429 ? `Both apps use the same name ${J(appName)} — try giving each app a unique name.`430 : `The app configs are missing "name" property that serves to distinct them.`;431 return new DetoxConfigError({432 message: `App collision detected in the selected configuration ${J(name)}.`,433 hint: `\434${hintMessage}435detox → ${preExistingAppPath.join(' → ')}:436${DetoxConfigError.inspectObj(config1, { depth: 0 })}437detox → ${appPath.join(' → ')}:438${DetoxConfigError.inspectObj(config2, { depth: 0 })}439Examine your Detox config${this._atPath()}`,440 });441 }442 noAppIsDefined(deviceType) {443 const name = this.configurationName;444 const [appType] = deviceAppTypes[deviceType] || [''];445 const [appPlatform] = appType.split('.');446 const appAlias = appType ? `myApp.${appPlatform}` : 'myApp';447 return new DetoxConfigError({448 message: `The ${J(name)} configuration has no defined "app" config.`,449 hint: `There should be an inlined object or an alias to the app config, e.g.:\n450{451 "apps": {452*-->"${appAlias}": {453| "type": "${appType || 'someAppType'}",454| "binaryPath": "path/to/app"455| },456| },457| "configurations": {458| ${J(name)}: {459*---- "app": "${appAlias}"460 ...461 }462 }463}464Examine your Detox config${this._atPath()}`,465 debugInfo: this._focusOnConfiguration(),466 inspectOptions: { depth: 0 }467 });468 }469 oldSchemaHasAppAndApps() {470 return new DetoxConfigError({471 message: `Your configuration ${J(this.configurationName)} appears to be in a legacy format, which can’t contain "app" or "apps".`,472 hint: `Remove "type" property from configuration and use "device" property instead:\n` +473 `a) "device": { "type": ${J(this._getSelectedConfiguration().type)}, ... }\n` +474 `b) "device": "<alias-to-device>" // you should add that device configuration to "devices" with the same key` +475 `\n\nCheck your Detox config${this._atPath()}`,476 debugInfo: this._focusOnConfiguration(this._ensureProperty('type', 'device')),477 inspectOptions: { depth: 2 },478 });479 }480 ambiguousAppAndApps() {481 return new DetoxConfigError({482 message: `You can't have both "app" and "apps" defined in the ${J(this.configurationName)} configuration.`,483 hint: 'Use "app" if you have a single app to test.' +484 '\nUse "apps" if you have multiple apps to test.' +485 `\n\nCheck your Detox config${this._atPath()}`,486 debugInfo: this._focusOnConfiguration(this._ensureProperty('app', 'apps')),487 inspectOptions: { depth: 2 },488 });489 }490 multipleAppsConfigArrayTypo() {491 return new DetoxConfigError({492 message: `Invalid type of the "app" property in the selected configuration ${J(this.configurationName)}.`,493 hint: 'Rename "app" to "apps" if you plan to work with multiple apps.' +494 `\n\nCheck your Detox config${this._atPath()}`,495 debugInfo: this._focusOnConfiguration(this._ensureProperty('app')),496 inspectOptions: { depth: 2 },497 });498 }499 multipleAppsConfigShouldBeArray() {500 return new DetoxConfigError({501 message: `Expected an array in "apps" property in the selected configuration ${J(this.configurationName)}.`,502 hint: 'Rename "apps" to "app" if you plan to work with a single app.' +503 '\nOtherwise, make sure "apps" contains a valid array of app aliases or inlined app configs.' +504 `\n\nCheck your Detox config${this._atPath()}`,505 debugInfo: this._focusOnConfiguration(this._ensureProperty('apps')),506 inspectOptions: { depth: 3 },507 });508 }509 // endregion510 // region composeSessionConfig511 invalidServerProperty() {512 return new DetoxConfigError({513 message: `session.server property is not a valid WebSocket URL`,514 hint: `Expected something like "ws://localhost:8099".\nCheck that in your Detox config${this._atPath()}`,515 inspectOptions: { depth: 3 },516 debugInfo: _.omitBy({517 session: _.get(this.contents, ['session']),518 ...this._focusOnConfiguration(c => _.pick(c, ['session'])),519 }, _.isEmpty),...

Full Screen

Full Screen

method-template.js

Source:method-template.js Github

copy

Full Screen

...77 * boolean value that indicates whether or not the parameter is78 * mandatory.79 */80 _setRequestParameters(paramType, params) {81 const requestParams = this._ensureProperty('RequestParameters', {});82 for(let param in params) {83 const key = `method.request.${paramType}.${param}`;84 requestParams[key] = !!(params[param]);85 }86 }87 /**88 * Assigns parent information to the template. This includes references to89 * API object and a parent resource object.90 *91 * @param {Object} dirInfo An object that contains hierarchical information92 * for the template.93 *94 * @return {Object} A reference to the template. Can be used to95 * chain multiple calls.96 */97 setParent(dirInfo) {98 this.properties.RestApiId = _resourceUtils.getRestApi(dirInfo);99 this.properties.ResourceId = _resourceUtils.getCurrentResource(dirInfo);100 return this;101 }102 /**103 * Sets the HttpMethod for the template.104 *105 * @param {String} verb The http verb.106 *107 * @return {Object} A reference to the template. Can be used to108 * chain multiple calls.109 */110 setHttpMethod(verb) {111 if(typeof verb !== 'string' || verb.length <= 0) {112 throw new Error('Invalid http verb specified (arg #1)');113 }114 this.properties.HttpMethod = verb.toUpperCase();;115 return this;116 }117 /**118 * Sets the authorizer for the template.119 *120 * @param {String} id The id of the authorizer. If a falsy value is121 * specified, authorization will be disabled.122 *123 * @return {Object} A reference to the template. Can be used to124 * chain multiple calls.125 */126 setAuthorizer(id) {127 if(!id) {128 this.properties.AuthorizationType = 'NONE';129 return this;130 }131 this.properties.AuthorizationType = 'CUSTOM';132 this.properties.AuthorizerId = { Ref: id };133 return this;134 }135 /**136 * Assigns a back end lambda function to the template.137 *138 * @param {String} lambdaFunction The name of the lambda function. A full139 * URI will be generated using this value.140 * @param {String} [role = '<% lambda_invoke_role %>'] An optional IAM role141 * name that will be used by the API gateway to call the lambda.142 *143 * @return {Object} A reference to the template. Can be used to144 * chain multiple calls.145 */146 setBackendLambda(lambdaFunction, role) {147 if(typeof lambdaFunction !== 'string' || lambdaFunction.length <= 0) {148 throw new Error('Invalid lambda function specified (arg #2)');149 }150 role = role || '<% lambda_invoke_role %>';151 const integration = this._ensureProperty('Integration');152 integration.Uri = _lambdaUtils.getLambdaUri(lambdaFunction);153 integration.Credentials = _iamUtils.getRoleUri(role);154 return this;155 }156 /**157 * Sets integration parameters to indicate a mock back end, meaning that158 * output from the request template transformation will be routed to the159 * response.160 *161 * @return {Object} A reference to the template. Can be used to162 * chain multiple calls.163 */164 setMockBackend() {165 const integration = this._ensureProperty('Integration');166 integration.Type = 'MOCK';167 integration.Uri = undefined;168 integration.Credentials = undefined;169 return this;170 }171 /**172 * Sets a request header parameter on the method template.173 *174 * @param {String} name The name of the parameter175 * @param {Boolean} [required=false] An optional parameter that176 * determines whether or not the parameter is mandatory.177 *178 * @return {Object} A reference to the template. Can be used to179 * chain multiple calls.180 */181 setRequestHeader(name, required) {182 if(typeof name !== 'string' || name.length <= 0) {183 throw new Error('Invalid name specified (arg #1)');184 }185 const params = { };186 params[name] = !!required;187 this._setRequestParameters('header', params);188 return this;189 }190 /**191 * Sets a request query string parameter on the method template.192 *193 * @param {String} name The name of the parameter194 * @param {Boolean} [required=false] An optional parameter that195 * determines whether or not the parameter is mandatory.196 *197 * @return {Object} A reference to the template. Can be used to198 * chain multiple calls.199 */200 setRequestQueryString(name, required) {201 if(typeof name !== 'string' || name.length <= 0) {202 throw new Error('Invalid name specified (arg #1)');203 }204 const params = { };205 params[name] = !!required;206 this._setRequestParameters('querystring', params);207 return this;208 }209 /**210 * Sets request path parameters on the method template.211 *212 * @param {String} name The name of the parameter213 * @param {Boolean} [required=false] An optional parameter that214 * determines whether or not the parameter is mandatory.215 *216 * @return {Object} A reference to the template. Can be used to217 * chain multiple calls.218 */219 setRequestPath(name, required) {220 if(typeof name !== 'string' || name.length <= 0) {221 throw new Error('Invalid name specified (arg #1)');222 }223 const params = { };224 params[name] = !!required;225 this._setRequestParameters('path', params);226 return this;227 }228 /**229 * Assigns request templates to the method template.230 *231 * @param {String} template The request template string.232 * @param {String} [contentType='application/json'] An optional content233 * type parameter for which the template will be applied.234 *235 * @return {Object} A reference to the template. Can be used to236 * chain multiple calls.237 */238 setRequestTemplate(template, contentType) {239 if(typeof template !== 'string' || template.length <= 0) {240 throw new Error('Invalid template specified (arg #1)');241 }242 if(typeof contentType !== 'string' || contentType.length <= 0) {243 contentType = 'application/json';244 }245 const requestTemplates = this._ensureProperty('Integration.RequestTemplates');246 requestTemplates[contentType] = template;247 return this;248 }249 /**250 * Assigns request models to the method template.251 *252 * @param {String} modelName The name of the model to assign.253 * @param {String} [contentType='application/json'] An optional content254 * type parameter for which the model will be assigned.255 *256 * @return {Object} A reference to the template. Can be used to257 * chain multiple calls.258 */259 setRequestModel(modelName, contentType) {260 if(typeof modelName !== 'string' || modelName.length <= 0) {261 throw new Error('Invalid modelName specified (arg #1)');262 }263 if(typeof contentType !== 'string' || contentType.length <= 0) {264 contentType = 'application/json';265 }266 const requestModels = this._ensureProperty('RequestModels');267 requestModels[contentType] = modelName;268 return this;269 }270 /**271 * Initializes the response integration with default values - response272 * codes and response templates.273 *274 * Assigns a list of standard integration response templates for common275 * response codes, including a dummy place holder for a 200 response code.276 *277 * Response codes for the templates will also be declared if they do not278 * exist.279 *280 * This method will overwrite any existing template assignments, and method281 * response declarations.282 *283 * @return {Object} A reference to the template. Can be used to284 * chain multiple calls.285 */286 setDefaultIntegrationResponses() {287 const integrationResponses = [];288 const methodResponses = [];289 // First add error responses.290 [291 { code: '400', pattern: '\\[((SchemaError)|(BadRequest))\\].*' },292 { code: '403', pattern: '\\[Unauthorized\\].*' },293 { code: '404', pattern: '\\[NotFound\\].*' },294 { code: '500', pattern: '\\[Error\\].*' }295 ].forEach((item) => {296 integrationResponses.push({297 StatusCode: item.code,298 SelectionPattern: item.pattern,299 ResponseTemplates: {300 'application/json': '{ "message": "$input.path(\'$.errorMessage\')" }'301 }302 });303 methodResponses.push({304 StatusCode: item.code,305 ResponseModels: {306 'application/json': 'Error'307 }308 });309 });310 // Add the default response (non error)311 integrationResponses.push({312 StatusCode: '200',313 ResponseTemplates: {314 'application/json': '{ "message": "Mapping not defined (200)" }'315 }316 });317 methodResponses.push({318 StatusCode: '200'319 });320 this.properties.MethodResponses = methodResponses;321 this._ensureProperty('Integration').IntegrationResponses = integrationResponses;322 return this;323 }324 /**325 * Initializes or overwrites a previously defined integration response326 * object. This method will also declare a method response for the specified327 * status code if one does not exist.328 *329 * @param {String} statusCode The status code for which the response is being330 * defined.331 * @param {String} [selectionPattern=undefined] An optional selection pattern332 * to use when matching responses to error message strings.333 *334 * @return {Object} A reference to the template. Can be used to335 * chain multiple calls.336 */337 setIntegrationResponse(statusCode, selectionPattern) {338 if(typeof statusCode !== 'string' || statusCode.length <= 0) {339 throw new Error('Invalid statusCode specified (arg #1)');340 }341 const integrationResponses = this._ensureProperty('Integration.IntegrationResponses', []);342 let intResp = integrationResponses.find((item) => {343 return item.StatusCode === statusCode;344 });345 if(!intResp) {346 intResp = { };347 integrationResponses.push(intResp);348 }349 intResp.StatusCode = statusCode;350 intResp.SelectionPattern = selectionPattern;351 const methodResponses = this._ensureProperty('MethodResponses', []);352 let metResp = methodResponses.find((item) => {353 return item.StatusCode === statusCode;354 });355 if(!metResp) {356 metResp = { };357 methodResponses.push(metResp);358 }359 metResp.StatusCode = statusCode;360 return this;361 }362 /**363 * Assigns response headers for specific codes. The method response object364 * for the code must exist. If not, this method will have no effect.365 *366 * @param {String} headerName The name of the header367 * @param {String} headerValue The value to assign to the header.368 * @param {String} [statusCode='200'] The status code to which the369 * response template will be assigned. This parameter will be370 * defaulted to '200' if omitted.371 *372 * @return {Object} A reference to the template. Can be used to373 * chain multiple calls.374 */375 setResponseHeader(headerName, headerValue, statusCode) {376 if(typeof headerName !== 'string' || headerName.length <= 0) {377 throw new Error('Invalid headerName specified (arg #1)');378 }379 if(typeof headerValue !== 'string' || headerValue.length <= 0) {380 throw new Error('Invalid headerValue specified (arg #2)');381 }382 if(typeof statusCode !== 'string' || statusCode.length <= 0) {383 statusCode = '200';384 }385 const integrationResponses = this._ensureProperty('Integration.IntegrationResponses', []);386 const methodResponses = this._ensureProperty('MethodResponses', []);387 let intResp = integrationResponses.find((item) => {388 return item.StatusCode === statusCode;389 });390 let metResp = methodResponses.find((item) => {391 return item.StatusCode === statusCode;392 });393 if(intResp && metResp) {394 metResp.ResponseParameters = metResp.ResponseParameters || {};395 metResp.ResponseParameters[`method.response.header.${headerName}`] = true;396 intResp.ResponseParameters = intResp.ResponseParameters || {};397 intResp.ResponseParameters[`method.response.header.${headerName}`] = headerValue;398 }399 return this;400 }401 /**402 * Assigns a response template for a specific code and content type. The403 * integration response object for the code must exist. If not, this method404 * will have no effect.405 *406 * @param {String} template A string that represents the template to be407 * assigned.408 * @param {String} [contentType='application/json'] An optional content409 * type parameter for which the template will be applied.410 * @param {String} [statusCode='200'] The status code to which the411 * response template will be assigned. This parameter will be412 * defaulted to '200' if omitted.413 *414 * @return {Object} A reference to the template. Can be used to415 * chain multiple calls.416 */417 setResponseTemplate(template, contentType, statusCode) {418 if(typeof template !== 'string' || template.length <= 0) {419 throw new Error('Invalid template specified (arg #1)');420 }421 if(typeof contentType !== 'string' || contentType.length <= 0) {422 contentType = 'application/json';423 }424 if(typeof statusCode !== 'string' || statusCode.length <= 0) {425 statusCode = '200';426 }427 const integrationResponses = this._ensureProperty('Integration.IntegrationResponses', []);428 const response = integrationResponses.find((item) => {429 return item.StatusCode === statusCode;430 });431 if(typeof response === 'object') {432 response.ResponseTemplates = response.ResponseTemplates || {};433 response.ResponseTemplates[contentType] = template;434 }435 return this;436 }437 /**438 * Assigns a response model for a specific status code and content type. The439 * method response object for the code must exist. If not, this method440 * will have no effect.441 *442 * @param {String} modelName The name of the model to assign.443 * @param {String} [contentType='application/json'] An optional content444 * type parameter for which the model will be assigned.445 * @param {String} [statusCode='200'] The status code to which the446 * response template will be assigned. This parameter will be447 * defaulted to '200' if omitted.448 *449 * @return {Object} A reference to the template. Can be used to450 * chain multiple calls.451 */452 setResponseModel(modelName, contentType, statusCode) {453 if(typeof modelName !== 'string' || modelName.length <= 0) {454 throw new Error('Invalid modelName specified (arg #1)');455 }456 if(typeof contentType !== 'string' || contentType.length <= 0) {457 contentType = 'application/json';458 }459 if(typeof statusCode !== 'string' || statusCode.length <= 0) {460 statusCode = '200';461 }462 const methodResponses = this._ensureProperty('MethodResponses', []);463 const response = methodResponses.find((item) => {464 return item.StatusCode === statusCode;465 });466 if(typeof response === 'object') {467 response.ResponseModels = response.ResponseModels || {};468 response.ResponseModels[contentType] = modelName;469 }470 return this;471 }472}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1if (typeof Object.prototype._ensureProperty != 'function') {2 Object.prototype._ensureProperty = function (propName) {3 if (!this.hasOwnProperty(propName)) {4 this[propName] = {};5 }6 };7}8if (typeof Object.prototype._ensureProperty != 'function') {9 Object.prototype._ensureProperty = function (propName) {10 if (!this.hasOwnProperty(propName)) {11 this[propName] = {};12 }13 };14}15if (typeof Object.prototype._ensureProperty != 'function') {16 Object.prototype._ensureProperty = function (propName) {17 if (!this.hasOwnProperty(propName)) {18 this[propName] = {};19 }20 };21}22if (typeof Object.prototype._ensureProperty != 'function') {23 Object.prototype._ensureProperty = function (propName) {24 if (!this.hasOwnProperty(propName)) {25 this[propName] = {};26 }27 };28}29if (typeof Object.prototype._ensureProperty != 'function') {30 Object.prototype._ensureProperty = function (propName) {31 if (!this.hasOwnProperty(propName)) {32 this[propName] = {};33 }34 };35}36if (typeof Object.prototype._ensureProperty != 'function') {37 Object.prototype._ensureProperty = function (propName) {38 if (!this.hasOwnProperty(propName)) {39 this[propName] = {};40 }41 };42}43if (typeof Object.prototype._ensureProperty != 'function') {44 Object.prototype._ensureProperty = function (propName) {45 if (!this.hasOwnProperty(propName)) {46 this[propName] = {};47 }48 };49}50if (typeof Object.prototype._ensureProperty != 'function') {51 Object.prototype._ensureProperty = function (propName) {52 if (!this.hasOwnProperty(propName)) {53 this[propName] = {};54 }55 };56}57if (typeof Object.prototype._ensureProperty != 'function') {58 Object.prototype._ensureProperty = function (propName)

Full Screen

Using AI Code Generation

copy

Full Screen

1var obj = {2 a: {3 b: {4 c: {5 }6 }7 }8};9var _ensureProperty = function (obj, path, value) {10 var pathArray = path.split('.');11 var last = pathArray.pop();12 var parent = pathArray.reduce(function (parent, key) {13 return parent[key];14 }, obj);15 parent[last] = value;16};17_ensureProperty(obj, 'a.b.c.d.e.f.g', 2);18_ensureProperty(obj, 'a.b.c.d.e.f.g', 3);19_ensureProperty(obj, 'a.b.c.d.h', 4);20_ensureProperty(obj, 'a.b.c.d.h', 5);21_ensureProperty(obj, 'a.b.c.d.e.f.g', 6);22_ensureProperty(obj, 'a.b.c.d.e.f.h', 7);23_ensureProperty(obj, 'a.b.c.d.e.f.h', 8);24_ensureProperty(obj, 'a.b.c.d.e.f.g', 9);25_ensureProperty(obj, 'a.b.c.d.e.f.g', 10);26_ensureProperty(obj, 'a.b.c.d.e.f.g', 11);27_ensureProperty(obj, 'a.b.c.d.e.f.g', 12);28_ensureProperty(obj, 'a.b.c.d.e.f.g', 13);29_ensureProperty(obj, 'a.b.c.d.e.f.g', 14);

Full Screen

Using AI Code Generation

copy

Full Screen

1var root = require('root');2root._ensureProperty('test', 'value');3console.log(root.test);4var root = require('root');5root._ensureProperty('test', 'value');6console.log(root.test);7var root = require('root');8root._ensureProperty('test', 'value');9console.log(root.test);10var root = require('root');11root._ensureProperty('test', 'value');12console.log(root.test);13var root = require('root');14root._ensureProperty('test', 'value');15console.log(root.test);16var root = require('root');17root._ensureProperty('test', 'value');18console.log(root.test);19var root = require('root');20root._ensureProperty('test', 'value');21console.log(root.test);22var root = require('root');23root._ensureProperty('test', 'value');24console.log(root.test);25var root = require('root');26root._ensureProperty('test', 'value');27console.log(root.test);28var root = require('root');29root._ensureProperty('test', 'value');30console.log(root.test);31var root = require('root');32root._ensureProperty('test', 'value');33console.log(root.test);34var root = require('root');35root._ensureProperty('test

Full Screen

Using AI Code Generation

copy

Full Screen

1var root = this;2var path = "a.b.c.d.e";3var value = "Hello World";4var result = root._ensureProperty(path, value);5console.log(result);6var root = this;7var path = "a.b.c.d.e";8var result = root._getProperty(path);9console.log(result);10var root = this;11var path = "a.b.c.d.e";12var value = "Hello World";13var result = root._setProperty(path, value);14console.log(result);15var root = this;16var path = "a.b.c.d.e";17var result = root._deleteProperty(path);18console.log(result);19var root = this;20var result = root._getProperties();21console.log(result);22var root = this;23var path = "a.b.c.d.e";24var result = root._getProperties(path);25console.log(result);26var root = this;27var path = "a.b.c.d.e";28var result = root._getProperties(path, true);29console.log(result);30var root = this;31var path = "a.b.c.d.e";32var result = root._getProperties(path, false);33console.log(result);34var root = this;35var result = root._getPropertyNames();36console.log(result);37var root = this;38var path = "a.b.c.d.e";39var result = root._getPropertyNames(path);40console.log(result);41var root = this;42var path = "a.b.c.d.e";43var result = root._getPropertyNames(path, true);44console.log(result);

Full Screen

Using AI Code Generation

copy

Full Screen

1var root = require('./root.js');2root._ensureProperty('a.b.c', 10);3### _ensureProperty(path, value, delimiter)4### _extend(target, source)5### _merge(target, source)6### _clone(source)7### _deepClone(source)8### _copy(source, target)9### _deepCopy(source, target)10### _isEmpty(obj)

Full Screen

Using AI Code Generation

copy

Full Screen

1var root = require('./root')2root._ensureProperty('test', 'hello world')3console.log(root.test)4module.exports = {5 _extend: function (target, source) {6 for (var key in source) {7 if (source.hasOwnProperty(key)) {8 }9 }10 }11}12var root = require('./root')13var obj1 = {name: 'John', age: 25}14var obj2 = {name: 'Peter', city: 'New York'}15var obj3 = root._extend(obj1, obj2)16console.log(obj3)17module.exports = {18 _has: function (obj, key) {19 return obj != null && hasOwnProperty.call(obj, key)20 }21}22var root = require('./root')23var obj = {name: 'John', age: 25}24console.log(root._has(obj, 'name'))25module.exports = {26 _isArguments: function (obj) {27 return Object.prototype.toString.call(obj) === '[object Arguments]'28 }29}30var root = require('./root')31var args = (function () { return arguments })()32console.log(root._isArguments(args))33module.exports = {34 _isArray: Array.isArray || function (obj) {35 return Object.prototype.toString.call(obj) === '[object Array]'36 }37}38var root = require('./root')39console.log(root._isArray([1, 2, 3]))40module.exports = {

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 root 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