Best JavaScript code snippet using puppeteer
activity.store.js
Source:activity.store.js
1const jsonCircular = require('circular-json');2const fs = require('fs');3const path = require('path');4const RestUtil = require('../utils/rest');5const SoapUtil = require('../utils/soap');6const log = require('../utils/logger');7let customerSegmentationXML;8fs.readFile(`${path.join(__dirname, '../templates')}/NBA_PolicyHolder_Template`, 'utf8', async (err, data) => {9 if (err) {10 log.logger.error(`Error when reading file: ${err}`);11 }12 customerSegmentationXML = data;13});14const connectionErrorMessage = [];15const getDataXMLJD = async (decoded, token) => {16 if (!customerSegmentationXML) {17 throw new Error('Error getDataXMLJD : Unable to find xml template');18 }19 let xml;20 xml = customerSegmentationXML;21 xml = xml.replace('[token]', token);22 xml = xml.replace('[accountId]', decoded.accountId);23 const soapRequest = {24 url: `${process.env.SOAP_BASE_URI}Service.asmx`,25 soapAction: 'Retrieve',26 body: xml27 };28 const soapRespBody = await SoapUtil.post(soapRequest);29 const accountDeMapping = new Map();30 const objectHasProperty = async (obj,prop) => {31 for (var p in obj) {32 if (obj.hasOwnProperty(p)) {33 if (p === prop) {34 return obj;35 } else if (obj[p] instanceof Object && objectHasProperty(obj[p], prop)) {36 return obj[p];37 }38 }39 }40 return null;41 }42 const hasProperty = await objectHasProperty(soapRespBody,'Property');43 if(hasProperty){44 const property = soapRespBody.RetrieveResponseMsg.Results.Properties.Property;45 for (let i = 0; i < property.length; i += 1) {46 accountDeMapping.set(property[i].Name, property[i].Value);47 }48 }49 else{50 log.logger.info('Soap Request Property Undefined');51 }52 return accountDeMapping;53};54const requestGetProductInformationJD = async (accountDeMapping, decodedArgs, token) => {55 var bodyStringRequest = {56 decisionId: decodedArgs.decisionId,57 platform: process.env.PLATFORM,58 audienceList: [{59 customerId: decodedArgs.clientId,60 microSegment: decodedArgs.microSegment,61 isOngoing: accountDeMapping.get('NBA_Ongoing_Interaction__c'),62 crmId: decodedArgs.crmId63 }64 ],65 campaign: {66 campaignId: decodedArgs.campaignId,67 campaignName: decodedArgs.campaignName,68 campaignType: decodedArgs.campaignType,69 campaignProductType: [70 decodedArgs.campaignProductType71 ],72 overrideContactFramwork: decodedArgs.overrideFramework73 }74 };75 var header = {76 'Content-Type': 'application/json',77 'Content-Length': bodyStringRequest.length78 };79 var mcRequest = {80 body: bodyStringRequest,81 headers: header,82 url: process.env.WS_URL83 };84 try {85 const { response, body } = await RestUtil.post(mcRequest);86 if (body) {87 const jsonValue = JSON.parse(body);88 if (jsonValue.status !== process.env.KO_STATUS_OK) {89 log.logger.info(`connectionErrorMessage - > ${body}`);90 connectionErrorMessage[0] = `${jsonValue.status}-${jsonValue.message}`;91 }92 }93 return body;94 }95 catch (exception) {96 throw new Error(exception);97 }98};99// to be refined100const updateDataExtensionDE = async (body, token, decodedArgs) => {101 const jsonValue = JSON.parse(body);102 let error = process.env.Error;103 if (connectionErrorMessage.length > 0) {104 jsonValue.status = error;105 for (let i = 0; i < connectionErrorMessage.length; i += 1) {106 if (connectionErrorMessage[i] !== undefined) {107 jsonValue.message = connectionErrorMessage[i];108 }109 log.logger.info(`MESSAGE VALUE - > ${jsonValue.message}`);110 }111 }112 else if (connectionErrorMessage.length === 0) {113 if(jsonValue.hasOwnProperty("offerProducts") !== true || jsonValue.offerProducts.length < 2 ){114 jsonValue.koStatus = process.env.KO_STATUS_YES;115 } 116 if (jsonValue.koStatus === process.env.KO_STATUS_NO && jsonValue.offerProducts.length >= 2) {117 log.logger.info(`offer Products${jsonValue.offerProducts}`);118 const offerProductsSorted = jsonValue.offerProducts.slice(0);119 offerProductsSorted.sort((a, b) => a.productRank - b.productRank);120 for (let i = 0; i < offerProductsSorted.length; i += 1) {121 jsonValue.offerProducts[i].productName = offerProductsSorted[i].productName;122 jsonValue.offerProducts[i].productCode = offerProductsSorted[i].productCode;123 jsonValue.offerProducts[i].componentCode = offerProductsSorted[i].componentCode;124 }125 }126 }127 let pkValue = decodedArgs.decisionId + '-' + decodedArgs.journeyStepCode;128 const bodyStringInsertRowDE = 129 [{130 keys: {131 pK: pkValue132 },133 values: {134 customerId: decodedArgs.clientId,135 PersonContactId: decodedArgs.contactId,136 CampaignId: decodedArgs.campaignId,137 journeyStepCode: decodedArgs.journeyStepCode,138 microSegment: decodedArgs.microSegment,139 CampaignAudienceId : decodedArgs.decisionId,140 Product1Name: (jsonValue.status !== error && jsonValue.offerProducts.length >= 2) ? jsonValue.offerProducts[0].productName : '',141 Product1Code: (jsonValue.status !== error && jsonValue.offerProducts.length >= 2) ? jsonValue.offerProducts[0].productCode : '',142 Product1Type: (jsonValue.status !== error && jsonValue.offerProducts.length >= 2) ? jsonValue.offerProducts[0].componentCode : '',143 Product2Name: (jsonValue.status !== error && jsonValue.offerProducts.length >= 2) ? jsonValue.offerProducts[1].productName : '',144 Product2Code: (jsonValue.status !== error && jsonValue.offerProducts.length >= 2) ? jsonValue.offerProducts[1].productCode : '',145 Product2Type: (jsonValue.status !== error && jsonValue.offerProducts.length >= 2) ? jsonValue.offerProducts[1].componentCode : '',146 koStatus: jsonValue.koStatus,147 Status: jsonValue.status,148 Message: jsonValue.message,149 channelMismatch: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.channelMismatch : ''),150 corporateClients: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.corporateClients : ''),151 underTrust: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.underTrust : ''),152 servicedBy: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.servicedBy : ''),153 customerStatus: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.customerStatus : ''),154 agentStatus: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.agentStatus : ''),155 controlGroup: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.controlGroup : ''),156 underBankruptcy: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.underBankruptcy : ''),157 foreignAddress: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.foreignAddress : ''),158 foreignMobileNumber: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.foreignMobileNumber : ''),159 phladeceased: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.phladeceased : ''),160 claimStatus: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.claimStatus : ''),161 claimType: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.claimType : ''),162 subClaimType: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.subClaimType : ''),163 failedTotalSumAssuredTest: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.failedTotalSumAssuredTest : ''),164 exclusionCodeImposed: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.exclusionCodeImposed : ''),165 extraMorality: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.extraMorality : ''),166 isSubstandard: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.isSubstandard : ''),167 amlwatchList: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.amlwatchList : ''),168 underwritingKOs: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.underwritingKOs : ''),169 existingProductsKOs: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.existingProductsKOs : ''),170 salesPersonKOs: (jsonValue.status !== error && jsonValue.hasOwnProperty("koReason") ? jsonValue.koReason.salesPersonKOs : '')171 }172 }];173 const upsertDEReqHeader = {174 'Content-Type': 'application/json',175 Authorization: `Bearer ${token}`176 };177 const upsertDERequest = {178 body: bodyStringInsertRowDE,179 headers: upsertDEReqHeader,180 url: `${process.env.REST_BASE_URI}hub/v1/dataevents/key:${process.env.DATA_EXTENSION_KEY}/rowset`181 };182 log.logger.info(`KO Result Request=>${JSON.stringify(upsertDERequest)}`);183 log.logger.info(`KO Result Req Body=>${JSON.stringify(bodyStringInsertRowDE)}`);184 try {185 const { insertDEResponse, insertDEBody } = await RestUtil.post(upsertDERequest);186 return insertDEBody;187 }188 catch (exception) {189 throw new Error(exception);190 }191};192class ActivityStore {193 static async save(req) {194 try {195 const payload = `Save===>${jsonCircular.stringify(req)}`;196 return payload;197 }198 catch (exception) {199 log.logger.error(`ActivityStore save error: ${exception}`);200 throw exception;201 }202 }203 static async publish(req) {204 try {205 const payload = 'Publish===>';206 return payload;207 }208 catch (exception) {209 log.logger.error(`ActivityStore publish error: ${exception}`);210 throw exception;211 }212 }213 static async validate(req) {214 try {215 const payload = `Validate===>${jsonCircular.stringify(req)}`;216 return payload;217 }218 catch (exception) {219 log.logger.error(`ActivityStore validate error: ${exception}`);220 throw exception;221 }222 }223 static async stop(req) {224 try {225 const payload = `Stop===>${jsonCircular.stringify(req)}`;226 return payload;227 }228 catch (exception) {229 log.logger.error(`ActivityStore stop error: ${exception}`);230 throw exception;231 }232 }233 static async execute(req) {234 try {235 log.logger.info(`ActivityStore execute => ${JSON.stringify(req.decoded)}`);236 const decodedArgs = req.decoded.inArguments[0];237 const accountDeMapping = await getDataXMLJD(decodedArgs, req.access_token);238 const getProductInfoBody = await239 requestGetProductInformationJD(accountDeMapping, decodedArgs, req.access_token);240 return await updateDataExtensionDE(getProductInfoBody, req.access_token, decodedArgs);241 }242 catch (exception) {243 log.logger.error(`ActivityStore execute error: ${exception}`);244 throw exception;245 }246 }247 248}...
ejson.js
Source:ejson.js
1EJSON = {};2var customTypes = {};3EJSON.addType = function(name, factory) {4 if (_.has(customTypes, name)) throw new Error("Type " + name + " already present");5 customTypes[name] = factory;6};7var isInfOrNan = function(obj) {8 return _.isNaN(obj) || 1/0 === obj || obj === -1/0;9};10var builtinConverters = [ {11 matchJSONValue: function(obj) {12 return _.has(obj, "$date") && 1 === _.size(obj);13 },14 matchObject: function(obj) {15 return obj instanceof Date;16 },17 toJSONValue: function(obj) {18 return {19 $date: obj.getTime()20 };21 },22 fromJSONValue: function(obj) {23 return new Date(obj.$date);24 }25}, {26 matchJSONValue: function(obj) {27 return _.has(obj, "$InfNaN") && 1 === _.size(obj);28 },29 matchObject: isInfOrNan,30 toJSONValue: function(obj) {31 var sign;32 sign = _.isNaN(obj) ? 0 : 1/0 === obj ? 1 : -1;33 return {34 $InfNaN: sign35 };36 },37 fromJSONValue: function(obj) {38 return obj.$InfNaN / 0;39 }40}, {41 matchJSONValue: function(obj) {42 return _.has(obj, "$binary") && 1 === _.size(obj);43 },44 matchObject: function(obj) {45 return "undefined" != typeof Uint8Array && obj instanceof Uint8Array || obj && _.has(obj, "$Uint8ArrayPolyfill");46 },47 toJSONValue: function(obj) {48 return {49 $binary: base64Encode(obj)50 };51 },52 fromJSONValue: function(obj) {53 return base64Decode(obj.$binary);54 }55}, {56 matchJSONValue: function(obj) {57 return _.has(obj, "$escape") && 1 === _.size(obj);58 },59 matchObject: function(obj) {60 if (_.isEmpty(obj) || _.size(obj) > 2) return false;61 return _.any(builtinConverters, function(converter) {62 return converter.matchJSONValue(obj);63 });64 },65 toJSONValue: function(obj) {66 var newObj = {};67 _.each(obj, function(value, key) {68 newObj[key] = EJSON.toJSONValue(value);69 });70 return {71 $escape: newObj72 };73 },74 fromJSONValue: function(obj) {75 var newObj = {};76 _.each(obj.$escape, function(value, key) {77 newObj[key] = EJSON.fromJSONValue(value);78 });79 return newObj;80 }81}, {82 matchJSONValue: function(obj) {83 return _.has(obj, "$type") && _.has(obj, "$value") && 2 === _.size(obj);84 },85 matchObject: function(obj) {86 return EJSON._isCustomType(obj);87 },88 toJSONValue: function(obj) {89 var jsonValue = Meteor._noYieldsAllowed(function() {90 return obj.toJSONValue();91 });92 return {93 $type: obj.typeName(),94 $value: jsonValue95 };96 },97 fromJSONValue: function(obj) {98 var typeName = obj.$type;99 if (!_.has(customTypes, typeName)) throw new Error("Custom EJSON type " + typeName + " is not defined");100 var converter = customTypes[typeName];101 return Meteor._noYieldsAllowed(function() {102 return converter(obj.$value);103 });104 }105} ];106EJSON._isCustomType = function(obj) {107 return obj && "function" == typeof obj.toJSONValue && "function" == typeof obj.typeName && _.has(customTypes, obj.typeName());108};109var adjustTypesToJSONValue = EJSON._adjustTypesToJSONValue = function(obj) {110 if (null === obj) return null;111 var maybeChanged = toJSONValueHelper(obj);112 if (void 0 !== maybeChanged) return maybeChanged;113 if ("object" != typeof obj) return obj;114 _.each(obj, function(value, key) {115 if ("object" != typeof value && void 0 !== value && !isInfOrNan(value)) return;116 var changed = toJSONValueHelper(value);117 if (changed) {118 obj[key] = changed;119 return;120 }121 adjustTypesToJSONValue(value);122 });123 return obj;124};125var toJSONValueHelper = function(item) {126 for (var i = 0; builtinConverters.length > i; i++) {127 var converter = builtinConverters[i];128 if (converter.matchObject(item)) return converter.toJSONValue(item);129 }130 return void 0;131};132EJSON.toJSONValue = function(item) {133 var changed = toJSONValueHelper(item);134 if (void 0 !== changed) return changed;135 if ("object" == typeof item) {136 item = EJSON.clone(item);137 adjustTypesToJSONValue(item);138 }139 return item;140};141var adjustTypesFromJSONValue = EJSON._adjustTypesFromJSONValue = function(obj) {142 if (null === obj) return null;143 var maybeChanged = fromJSONValueHelper(obj);144 if (maybeChanged !== obj) return maybeChanged;145 if ("object" != typeof obj) return obj;146 _.each(obj, function(value, key) {147 if ("object" == typeof value) {148 var changed = fromJSONValueHelper(value);149 if (value !== changed) {150 obj[key] = changed;151 return;152 }153 adjustTypesFromJSONValue(value);154 }155 });156 return obj;157};158var fromJSONValueHelper = function(value) {159 if ("object" == typeof value && null !== value && 2 >= _.size(value) && _.all(value, function(v, k) {160 return "string" == typeof k && "$" === k.substr(0, 1);161 })) for (var i = 0; builtinConverters.length > i; i++) {162 var converter = builtinConverters[i];163 if (converter.matchJSONValue(value)) return converter.fromJSONValue(value);164 }165 return value;166};167EJSON.fromJSONValue = function(item) {168 var changed = fromJSONValueHelper(item);169 if (changed === item && "object" == typeof item) {170 item = EJSON.clone(item);171 adjustTypesFromJSONValue(item);172 return item;173 }174 return changed;175};176EJSON.stringify = function(item, options) {177 var json = EJSON.toJSONValue(item);178 return options && (options.canonical || options.indent) ? EJSON._canonicalStringify(json, options) : JSON.stringify(json);179};180EJSON.parse = function(item) {181 if ("string" != typeof item) throw new Error("EJSON.parse argument should be a string");182 return EJSON.fromJSONValue(JSON.parse(item));183};184EJSON.isBinary = function(obj) {185 return !!("undefined" != typeof Uint8Array && obj instanceof Uint8Array || obj && obj.$Uint8ArrayPolyfill);186};187EJSON.equals = function(a, b, options) {188 var i;189 var keyOrderSensitive = !!(options && options.keyOrderSensitive);190 if (a === b) return true;191 if (_.isNaN(a) && _.isNaN(b)) return true;192 if (!a || !b) return false;193 if (!("object" == typeof a && "object" == typeof b)) return false;194 if (a instanceof Date && b instanceof Date) return a.valueOf() === b.valueOf();195 if (EJSON.isBinary(a) && EJSON.isBinary(b)) {196 if (a.length !== b.length) return false;197 for (i = 0; a.length > i; i++) if (a[i] !== b[i]) return false;198 return true;199 }200 if ("function" == typeof a.equals) return a.equals(b, options);201 if ("function" == typeof b.equals) return b.equals(a, options);202 if (a instanceof Array) {203 if (!(b instanceof Array)) return false;204 if (a.length !== b.length) return false;205 for (i = 0; a.length > i; i++) if (!EJSON.equals(a[i], b[i], options)) return false;206 return true;207 }208 switch (EJSON._isCustomType(a) + EJSON._isCustomType(b)) {209 case 1:210 return false;211 case 2:212 return EJSON.equals(EJSON.toJSONValue(a), EJSON.toJSONValue(b));213 }214 var ret;215 if (keyOrderSensitive) {216 var bKeys = [];217 _.each(b, function(val, x) {218 bKeys.push(x);219 });220 i = 0;221 ret = _.all(a, function(val, x) {222 if (i >= bKeys.length) return false;223 if (x !== bKeys[i]) return false;224 if (!EJSON.equals(val, b[bKeys[i]], options)) return false;225 i++;226 return true;227 });228 return ret && i === bKeys.length;229 }230 i = 0;231 ret = _.all(a, function(val, key) {232 if (!_.has(b, key)) return false;233 if (!EJSON.equals(val, b[key], options)) return false;234 i++;235 return true;236 });237 return ret && _.size(b) === i;238};239EJSON.clone = function(v) {240 var ret;241 if ("object" != typeof v) return v;242 if (null === v) return null;243 if (v instanceof Date) return new Date(v.getTime());244 if (v instanceof RegExp) return v;245 if (EJSON.isBinary(v)) {246 ret = EJSON.newBinary(v.length);247 for (var i = 0; v.length > i; i++) ret[i] = v[i];248 return ret;249 }250 if (_.isArray(v) || _.isArguments(v)) {251 ret = [];252 for (i = 0; v.length > i; i++) ret[i] = EJSON.clone(v[i]);253 return ret;254 }255 if ("function" == typeof v.clone) return v.clone();256 if (EJSON._isCustomType(v)) return EJSON.fromJSONValue(EJSON.clone(EJSON.toJSONValue(v)), true);257 ret = {};258 _.each(v, function(value, key) {259 ret[key] = EJSON.clone(value);260 });261 return ret;262};...
Cesium3DTileFeatureTable.js
Source:Cesium3DTileFeatureTable.js
1define([2 '../Core/ComponentDatatype',3 '../Core/defaultValue',4 '../Core/defined'5 ], function(6 ComponentDatatype,7 defaultValue,8 defined) {9 'use strict';10 /**11 * @private12 */13 function Cesium3DTileFeatureTable(featureTableJson, featureTableBinary) {14 this.json = featureTableJson;15 this.buffer = featureTableBinary;16 this._cachedTypedArrays = {};17 this.featuresLength = 0;18 }19 function getTypedArrayFromBinary(featureTable, semantic, componentType, componentLength, count, byteOffset) {20 var cachedTypedArrays = featureTable._cachedTypedArrays;21 var typedArray = cachedTypedArrays[semantic];22 if (!defined(typedArray)) {23 typedArray = ComponentDatatype.createArrayBufferView(componentType, featureTable.buffer.buffer, featureTable.buffer.byteOffset + byteOffset, count * componentLength);24 cachedTypedArrays[semantic] = typedArray;25 }26 return typedArray;27 }28 function getTypedArrayFromArray(featureTable, semantic, componentType, array) {29 var cachedTypedArrays = featureTable._cachedTypedArrays;30 var typedArray = cachedTypedArrays[semantic];31 if (!defined(typedArray)) {32 typedArray = ComponentDatatype.createTypedArray(componentType, array);33 cachedTypedArrays[semantic] = typedArray;34 }35 return typedArray;36 }37 Cesium3DTileFeatureTable.prototype.getGlobalProperty = function(semantic, componentType, componentLength) {38 var jsonValue = this.json[semantic];39 if (!defined(jsonValue)) {40 return undefined;41 }42 if (defined(jsonValue.byteOffset)) {43 componentType = defaultValue(componentType, ComponentDatatype.UNSIGNED_INT);44 componentLength = defaultValue(componentLength, 1);45 return getTypedArrayFromBinary(this, semantic, componentType, componentLength, 1, jsonValue.byteOffset);46 }47 return jsonValue;48 };49 Cesium3DTileFeatureTable.prototype.getPropertyArray = function(semantic, componentType, componentLength) {50 var jsonValue = this.json[semantic];51 if (!defined(jsonValue)) {52 return undefined;53 }54 if (defined(jsonValue.byteOffset)) {55 if (defined(jsonValue.componentType)) {56 componentType = ComponentDatatype.fromName(jsonValue.componentType);57 }58 return getTypedArrayFromBinary(this, semantic, componentType, componentLength, this.featuresLength, jsonValue.byteOffset);59 }60 return getTypedArrayFromArray(this, semantic, componentType, jsonValue);61 };62 Cesium3DTileFeatureTable.prototype.getProperty = function(semantic, componentType, componentLength, featureId, result) {63 var jsonValue = this.json[semantic];64 if (!defined(jsonValue)) {65 return undefined;66 }67 var typedArray = this.getPropertyArray(semantic, componentType, componentLength);68 if (componentLength === 1) {69 return typedArray[featureId];70 }71 for (var i = 0; i < componentLength; ++i) {72 result[i] = typedArray[componentLength * featureId + i];73 }74 return result;75 };76 return Cesium3DTileFeatureTable;...
test-json-request.js
Source:test-json-request.js
1'use strict'2var server = require('./server')3 , request = require('../index')4 , tape = require('tape')5var s = server.createServer()6tape('setup', function(t) {7 s.listen(s.port, function() {8 t.end()9 })10})11function testJSONValue(testId, value) {12 tape('test ' + testId, function(t) {13 var testUrl = '/' + testId14 s.on(testUrl, server.createPostJSONValidator(value, 'application/json'))15 var opts = {16 method: 'PUT',17 uri: s.url + testUrl,18 json: true,19 body: value20 }21 request(opts, function (err, resp, body) {22 t.equal(err, null)23 t.equal(resp.statusCode, 200)24 t.deepEqual(body, value)25 t.end()26 })27 })28}29function testJSONValueReviver(testId, value, reviver, revivedValue) {30 tape('test ' + testId, function(t) {31 var testUrl = '/' + testId32 s.on(testUrl, server.createPostJSONValidator(value, 'application/json'))33 var opts = {34 method: 'PUT',35 uri: s.url + testUrl,36 json: true,37 jsonReviver: reviver,38 body: value39 }40 request(opts, function (err, resp, body) {41 t.equal(err, null)42 t.equal(resp.statusCode, 200)43 t.deepEqual(body, revivedValue)44 t.end()45 })46 })47}48function testJSONValueReplacer(testId, value, replacer, replacedValue) {49 tape('test ' + testId, function(t) {50 var testUrl = '/' + testId51 s.on(testUrl, server.createPostJSONValidator(replacedValue, 'application/json'))52 var opts = {53 method: 'PUT',54 uri: s.url + testUrl,55 json: true,56 jsonReplacer: replacer,57 body: value58 }59 request(opts, function (err, resp, body) {60 t.equal(err, null)61 t.equal(resp.statusCode, 200)62 t.deepEqual(body, replacedValue)63 t.end()64 })65 })66}67testJSONValue('jsonNull', null)68testJSONValue('jsonTrue', true)69testJSONValue('jsonFalse', false)70testJSONValue('jsonNumber', -289365.2938)71testJSONValue('jsonString', 'some string')72testJSONValue('jsonArray', ['value1', 2, null, 8925.53289, true, false, ['array'], { object: 'property' }])73testJSONValue('jsonObject', {74 trueProperty: true,75 falseProperty: false,76 numberProperty: -98346.34698,77 stringProperty: 'string',78 nullProperty: null,79 arrayProperty: ['array'],80 objectProperty: { object: 'property' }81})82testJSONValueReviver('jsonReviver', -48269.592, function (k, v) {83 return v * -184}, 48269.592)85testJSONValueReviver('jsonReviverInvalid', -48269.592, 'invalid reviver', -48269.592)86testJSONValueReplacer('jsonReplacer', -48269.592, function (k, v) {87 return v * -188}, 48269.592)89testJSONValueReplacer('jsonReplacerInvalid', -48269.592,'invalid replacer', -48269.592) 90testJSONValueReplacer('jsonReplacerObject', {foo: 'bar'}, function (k, v) {91 return v.toUpperCase ? v.toUpperCase() : v92}, {foo: 'BAR'})93tape('missing body', function (t) {94 s.on('/missing-body', function (req, res) {95 t.equal(req.headers['content-type'], undefined)96 res.end()97 })98 request({url:s.url + '/missing-body', json:true}, function () {99 t.end()100 })101})102tape('cleanup', function(t) {103 s.close(function() {104 t.end()105 })...
localDb.js
Source:localDb.js
1import AsyncStorage from '@react-native-async-storage/async-storage';2// STORAGE KEYS3const globalPostStorageKey = "@StorageKeyGlobalPost"4const hotpostStorageKey = "@StorageKeyHotPost"5const followingPostStorageKey = "@StorageKeyFlwPost"6const recentPostStorageKey = "@StorageKeyRecentPost"7const profileStorageKey = "@StorageKeyProfile"8export const setGlobalPost = async (value) => {9 try {10 11 const jsonValue = JSON.stringify(getLatestPost(value))12 13 await AsyncStorage.setItem(globalPostStorageKey, jsonValue)14 } catch (e) {15 // saving error16 }17}18export const getGlobalPost = async () => {19 try {20 const jsonValue = await AsyncStorage.getItem(globalPostStorageKey)21 return jsonValue != null ? JSON.parse(jsonValue) : null;22 } catch(e) {23 // error reading value24 }25}26export const setHotPost = async (value)=> {27 try {28 const jsonValue = JSON.stringify(getLatestPost(value))29 30 await AsyncStorage.setItem(hotpostStorageKey, jsonValue)31 } catch (e) {32 // saving error33 }34}35export const getHotPost = async () => {36 try {37 const jsonValue = await AsyncStorage.getItem(hotpostStorageKey)38 return jsonValue != null ? JSON.parse(jsonValue) : null;39 } catch(e) {40 // error reading value41 }42}43export const setFollowingPost = async (value)=> {44 try {45 const jsonValue =JSON.stringify(getLatestPost(value))46 await AsyncStorage.setItem(followingPostStorageKey, jsonValue)47 } catch (e) {48 // saving error49 }50}51export const getFollowingPost = async () => {52 try {53 const jsonValue = await AsyncStorage.getItem(followingPostStorageKey)54 return jsonValue != null ? JSON.parse(jsonValue) : null;55 } catch(e) {56 // error reading value57 }58}59export const setRecentPost = async (value)=> {60 try {61 const jsonValue = JSON.stringify(getLatestPost(value))62 await AsyncStorage.setItem(recentPostStorageKey, jsonValue)63 } catch (e) {64 // saving error65 }66}67export const getRecentPost = async () => {68 try {69 const jsonValue = await AsyncStorage.getItem(recentPostStorageKey)70 return jsonValue != null ? JSON.parse(jsonValue) : null;71 } catch(e) {72 // error reading value73 }74}75export const setProfile = async (value)=> {76 try {77 const jsonValue = JSON.stringify(getLatestPost(value))78 await AsyncStorage.setItem(profileStorageKey, jsonValue)79 } catch (e) {80 // saving error81 }82}83export const getProfile = async () => {84 try {85 const jsonValue = await AsyncStorage.getItem(profileStorageKey)86 return jsonValue != null ? JSON.parse(jsonValue) : null;87 } catch(e) {88 // error reading value89 }90}91getLatestPost = (value) => {92 if(value.length > 9){93 return value.slice(Math.max(arr.length - 10, 0))94 }95 return value ...
activity.formatter.js
Source:activity.formatter.js
1const getDataExtensionIDE = (body) => {2 const jsonValue = JSON.parse(body);3 const statusField = {4 koStatusValue = jsonValue.koStatus,5 statusValue = jsonValue.status,6 messageValue = jsonValue.message,7 }8 const koReasonFields = {9 channelMismatchValue = jsonValue.koReason.channelMismatch,10 corporateClientsValue = jsonValue.koReason.corporateClients,11 underTrustValue = jsonValue.koReason.underTrust,12 servicedByValue = jsonValue.koReason.servicedBy,13 customerStatusValue = jsonValue.koReason.customerStatus,14 agentStatusValue = jsonValue.koReason.agentStatus,15 controlGroupValue = jsonValue.koReason.controlGroup,16 underBankruptcyValue = jsonValue.koReason.underBankruptcy,17 foreignAddressValue = jsonValue.koReason.foreignAddress,18 foreignMobileNumberValue = jsonValue.koReason.foreignMobileNumber,19 phladeceasedValue = jsonValue.koReason.phladeceased,20 claimStatusValue = jsonValue.koReason.claimStatus,21 claimTypeValue = jsonValue.koReason.claimType,22 subClaimTypeValue = jsonValue.koReason.subClaimType,23 failedTotalSumAssuredTestValue = jsonValue.koReason.failedTotalSumAssuredTest,24 exclusionCodeImposedValue = jsonValue.koReason.exclusionCodeImposed,25 extraMoralityValue = jsonValue.koReason.extraMorality,26 isSubstandardValue = jsonValue.koReason.isSubstandard,27 amlwatchListValue = jsonValue.koReason.amlwatchList,28 underwritingKOsValue = jsonValue.koReason.underwritingKOs,29 existingProductsKOsValue = jsonValue.koReason.existingProductsKOs,30 salesPersonKOsValue = jsonValue.koReason.salesPersonKOs,31 }32 return {statusField, koReasonFields}...
custom_models_for_tests.js
Source:custom_models_for_tests.js
1function Address (city, state) {2 this.city = city;3 this.state = state;4}5Address.prototype = {6 constructor: Address,7 typeName: function () {8 return "Address";9 },10 toJSONValue: function () {11 return {12 city: this.city,13 state: this.state14 };15 }16}17EJSON.addType("Address", function fromJSONValue(value) {18 return new Address(value.city, value.state);19});20function Person (name, dob, address) {21 this.name = name;22 this.dob = dob;23 this.address = address;24}25Person.prototype = {26 constructor: Person,27 typeName: function () {28 return "Person";29 },30 toJSONValue: function () {31 return {32 name: this.name,33 dob: EJSON.toJSONValue(this.dob),34 address: EJSON.toJSONValue(this.address)35 };36 }37}38_.extend(Person, {39 fromJSONValue: function(value) {40 return new Person(41 value.name,42 EJSON.fromJSONValue(value.dob),43 EJSON.fromJSONValue(value.address)44 );45 }46});47EJSON.addType("Person", Person.fromJSONValue);48function Holder (content) {49 this.content = content;50}51Holder.prototype = {52 constructor: Holder,53 typeName: function () {54 return "Holder";55 },56 toJSONValue: function () {57 return this.content;58 }59}60_.extend(Holder, {61 fromJSONValue: function(value) {62 return new Holder(value);63 }64});65EJSON.addType("Holder", Holder.fromJSONValue);66_.extend(EJSONTest, {67 Address: Address,68 Person: Person,69 Holder: Holder...
strategy.d.ts
Source:strategy.d.ts
1import { JsonValue } from '../../json';2import { JobDescription, JobHandler } from './api';3export declare namespace strategy {4 type JobStrategy<A extends JsonValue = JsonValue, I extends JsonValue = JsonValue, O extends JsonValue = JsonValue> = (handler: JobHandler<A, I, O>, options?: Partial<Readonly<JobDescription>>) => JobHandler<A, I, O>;5 /**6 * Creates a JobStrategy that serializes every call. This strategy can be mixed between jobs.7 */8 function serialize<A extends JsonValue = JsonValue, I extends JsonValue = JsonValue, O extends JsonValue = JsonValue>(): JobStrategy<A, I, O>;9 /**10 * Creates a JobStrategy that will always reuse a running job, and restart it if the job ended.11 * @param replayMessages Replay ALL messages if a job is reused, otherwise just hook up where it12 * is.13 */14 function reuse<A extends JsonValue = JsonValue, I extends JsonValue = JsonValue, O extends JsonValue = JsonValue>(replayMessages?: boolean): JobStrategy<A, I, O>;15 /**16 * Creates a JobStrategy that will reuse a running job if the argument matches.17 * @param replayMessages Replay ALL messages if a job is reused, otherwise just hook up where it18 * is.19 */20 function memoize<A extends JsonValue = JsonValue, I extends JsonValue = JsonValue, O extends JsonValue = JsonValue>(replayMessages?: boolean): JobStrategy<A, I, O>;...
Using AI Code Generation
1(async () => {2 const browser = await puppeteer.launch();3 const page = await browser.newPage();4 await page.waitForSelector('input[name="q"]');5 await page.type('input[name="q"]', 'puppeteer');6 await page.click('input[type="submit"]');7 await page.waitForSelector('h3');8 const result = await page.evaluate(() => {9 const anchors = Array.from(document.querySelectorAll('h3'));10 return anchors.map(anchor => anchor.textContent);11 });12 console.log(result);13 await browser.close();14})();15(async () => {16 const browser = await puppeteer.launch();17 const page = await browser.newPage();18 await page.waitForSelector('input[name="q"]');19 await page.type('input[name="q"]', 'puppeteer');20 await page.click('input[type="submit"]');21 await page.waitForSelector('h3');22 const result = await page.evaluate(() => {23 const anchors = Array.from(document.querySelectorAll('h3'));24 return anchors.map(anchor => anchor.textContent);25 });26 console.log(result);27 await browser.close();28})();29(async () => {30 const browser = await puppeteer.launch();31 const page = await browser.newPage();32 await page.waitForSelector('input[name="q"]');33 await page.type('input[name="q"]', 'puppeteer');34 await page.click('input[type="submit"]');35 await page.waitForSelector('h3');36 const result = await page.evaluate(() => {37 const anchors = Array.from(document.querySelectorAll('h3'));38 return anchors.map(anchor => anchor.textContent);39 });40 console.log(result);41 await browser.close();42})();43(async () => {44 const browser = await puppeteer.launch();45 const page = await browser.newPage();46 await page.waitForSelector('input[name="q"]');47 await page.type('input[name="q"]', 'puppeteer');48 await page.click('input[type="submit"]');49 await page.waitForSelector('h3');
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!