How to use subKey method in Best

Best JavaScript code snippet using best

index.ts

Source:index.ts Github

copy

Full Screen

1//list data2export const FB_INIT_VAL = 'FB_INIT_VAL';3export const FB_CHILD_ADDED = 'FB_CHILD_ADDED';4export const FB_CHILD_WILL_REMOVE = 'FB_CHILD_WILL_REMOVE';5export const FB_CHILD_REMOVED = 'FB_CHILD_REMOVED';6export const FB_CHILD_WILL_CHANGE = 'FB_CHILD_WILL_CHANGE';7export const FB_CHILD_CHANGED = 'FB_CHILD_CHANGED';8//value data9export const FB_VALUE = 'FB_VALUE';10import importedAutoSubscriber from './autoSubscriber';11export const autoSubscriber = importedAutoSubscriber;12export { createAutoSubscriber } from './autoSubscriber';13export { asDotGraph, asNodesAndEdges, defaultMakeVisNodeProps } from './subscriptionGraph';14interface ForEachChild {15 childSubs: (childKey: string | number, ...args) => Array<Sub>,16 args?: Array<any>17 store?: any18}19interface ForFields {20 fieldKey: string | number,21 fieldSubs: (fieldVal: any, ...args) => Array<Sub>,22 args?: Array<any>,23 store?: any24}25export interface Sub {26 subKey: string,27 asValue?: boolean,28 asList?: boolean,29 childSubs?: (childKey: string | number, ...args) => Array<Sub>,30 forEachChild?: ForEachChild,31 forFields?: Array<ForFields>,32 fieldSubs?: any //new more terse format33}34//credit to js-promise-defer on github35function defer(deferred) {36 deferred.promise = new Promise(function (resolve, reject) {37 deferred.resolve = resolve;38 deferred.reject = reject;39 });40}41function fieldSubsToForFields(sub: Sub) {42 const fieldSubs = sub.fieldSubs;43 if (!fieldSubs) return [];44 return Object.keys(fieldSubs || {}).map((key) => {45 const getFieldSubs = fieldSubs[key];46 return {47 fieldKey: key,48 fieldSubs: getFieldSubs49 };50 }51 );52}53//To detect subscriber cycles, keep track of which subscribes are done from "outside" as parentSubKey="_root".54//The rest of subscribes are due to subscribing to child data.55const rootSubKey = '_root';56//Firebase 3.x: snapshot.key() has been replaced with snapshot.key57let getKey = function(snapshot) {58 if (typeof snapshot.key == 'function') {59 console.log('firebase-nest: detected pre-3.x firebase snapshot.key()');60 getKey = legacyGetKey;61 return legacyGetKey(snapshot);62 }63 console.log('firebase-nest: detected ^3.x firebase snapshot.key');64 getKey = newGetKey;65 return newGetKey(snapshot);66};67function legacyGetKey(snapshot) {68 return snapshot.key();69}70function newGetKey(snapshot) {71 return snapshot.key;72}73export default function createSubscriber({onData,74 onSubscribed,75 onUnsubscribed,76 resolveFirebaseQuery,77 onWillSubscribe,78 onWillUnsubscribe,79 onError,80 doNotDetectCycles}) {81 function reportError(error) {82 if (onError && typeof onError === 'function') {83 onError(error);84 }85 }86 //let disallowSubscriptions = false;87 const subscribedRegistry = {};88 const promisesBySubKey = {};89 const self = {90 subscribeSubsWithPromise91 };92 function loadedPromise(subKey) {93 if (promisesBySubKey[subKey]) {94 return promisesBySubKey[subKey].promise;95 }96 promisesBySubKey[subKey] = {};97 defer(promisesBySubKey[subKey]);98 return promisesBySubKey[subKey].promise;99 }100 function subsLoaded(subs : Array<Sub>) {101 return Promise.all((subs || []).map(sub => loadedPromise(sub.subKey)));102 }103 if (!onData || !resolveFirebaseQuery) {104 console.error('createNestedFirebaseSubscriber: missing onData or resolveFirebaseQuery callback');105 return;106 }107 function subscribeToField(sub : Sub, forField, fieldKey, fieldVal, promises) {108 const store = (forField.store ? forField.store : self);109 var fieldSubs = forField.fieldSubs(fieldVal, ...(forField.args || [])) || [];110 const {unsubscribe, promise} = store.subscribeSubsWithPromise(fieldSubs, sub.subKey);111 if (!subscribedRegistry[sub.subKey]) {112 //edge case - roll back subscribe if somehow our parent got unsubscribed by on* callbacks113 unsubscribe();114 return;115 };116 subscribedRegistry[sub.subKey].fieldUnsubs[fieldKey] = unsubscribe;117 if (promises) {118 promises.push(promise);119 }120 }121 function subscribeToFields(sub : Sub, val, promises?) {122 if (!subscribedRegistry[sub.subKey]) return;123 const oldFieldUnsubs = Object.assign({}, subscribedRegistry[sub.subKey].fieldUnsubs || {});124 subscribedRegistry[sub.subKey].fieldUnsubs = {};125 //Subscribe based on new fields in val126 const forFields = (sub.fieldSubs ? fieldSubsToForFields(sub) : sub.forFields) || [];127 if (forFields.constructor !== Array) {128 console.error('ERROR: forFields must be an array: ',forFields);129 } else {130 if (val !== null && (typeof val == 'object')) {131 val = val || {};132 ((forFields || []) as any[]).forEach((forField : ForFields) => {133 if (!forField.fieldKey || !forField.fieldSubs) {134 console.error('ERROR: each element in forFields must have fieldKey and fieldSubs keys');135 return;136 }137 const fieldVal = val[forField.fieldKey];138 if (fieldVal !== undefined) {139 subscribeToField(sub, forField, forField.fieldKey, fieldVal, promises);140 }141 })142 }143 }144 //Unsubscribe old fields145 Object.keys(oldFieldUnsubs || {}).forEach(field => {146 const unsub = oldFieldUnsubs[field];147 unsub();148 });149 }150 function subscribeToChildData(sub : Sub, childKey, childVal, promises?) {151 if (!sub.forEachChild && !sub.childSubs) return;152 const getChildSubs = sub.forEachChild ? sub.forEachChild.childSubs : sub.childSubs;153 if (!getChildSubs) {154 console.error(`ERROR: forEachChild must have a childSubs key - a function that returns a subs array and takes a 155 childKey and other optional args specified in forEachChild.args`);156 }157 const store = (sub.forEachChild && sub.forEachChild.store ? sub.forEachChild.store : self);158 const childSubs = (sub.forEachChild ? getChildSubs(childKey, ...(sub.forEachChild.args||[]), childVal) : getChildSubs(childKey, childVal)) || [];159 const {unsubscribe, promise} = store.subscribeSubsWithPromise(childSubs, sub.subKey);160 if (!subscribedRegistry[sub.subKey]) {161 //roll back if parent got unsubscribed by on* callbacks162 unsubscribe();163 return;164 };165 subscribedRegistry[sub.subKey].childUnsubs[childKey] = unsubscribe;166 if (promises) {167 promises.push(promise);168 }169 }170 function check(type, sub) {171 if (!subscribedRegistry[sub.subKey]) {172 console.error('Error for '+sub.subKey+', got '+type+' firebase callback but not subscribed!');173 return false;174 }175 return true;176 }177 function handleFbError(sub) {178 return (error) => {179 if (subscribedRegistry[sub.subKey]) {180 const path = sub.path ? sub.path + ' ' : '';181 const errorCode = sub.subKey + ' ' + path + 'Firebase error: ' + ((error || {}).code || 'unknown error');182 reportError(errorCode);183 if (promisesBySubKey[sub.subKey]) {184 promisesBySubKey[sub.subKey].reject(errorCode);185 }186 }187 }188 }189 function detectAndReportSubscribeCycle(subKey) {190 //Check whether this subKey has itself in the parent chain, and if so, reject the promise191 const trail = detectSubscribeCycle(subKey,192 Object.keys(subscribedRegistry[subKey].parentSubKeys), [subKey], {});193 if (trail) {194 const error = 'Cycle detected: ' + trail.join('<-');195 //If there's a cycle (for ex. subKey A subscribed B which subscribed A), we will never resolve, so reject the Promise196 //TODO only reject if we haven't yet resolved197 if (promisesBySubKey[subKey]) {198 promisesBySubKey[subKey].reject(error);199 }200 reportError(error);201 }202 }203 function executeListSubscribeAction(sub : Sub, parentSubKey) {204 if (subscribedRegistry[sub.subKey]) {205 //Already subscribed, just increment ref count206 subscribedRegistry[sub.subKey].refCount++;207 if (parentSubKey) {208 const parentSubKeys = subscribedRegistry[sub.subKey].parentSubKeys;209 if (!parentSubKeys[parentSubKey]) {210 parentSubKeys[parentSubKey] = 1;211 } else {212 parentSubKeys[parentSubKey]++;213 }214 }215 //Check whether this subKey has itself in the parent chain, and if so, reject the promise216 if (!doNotDetectCycles) {217 detectAndReportSubscribeCycle(sub.subKey);218 }219 return;220 }221 var ref = resolveFirebaseQuery(sub);222 var gotInitVal = false;223 subscribedRegistry[sub.subKey] = {224 refCount: 1,225 ref: ref,226 parentSubKeys: {},227 childUnsubs: {},228 fieldUnsubs: {},229 refHandles: {}230 };231 if (parentSubKey) {232 subscribedRegistry[sub.subKey].parentSubKeys[parentSubKey] = 1;233 }234 loadedPromise(sub.subKey);235 const thePromise = promisesBySubKey[sub.subKey];236 const errorHandler = handleFbError(sub);237 subscribedRegistry[sub.subKey].refHandles.child_added = ref.on('child_added', function(snapshot) {238 if (!gotInitVal) return;239 if (!check('child_added', sub)) return;240 subscribeToChildData(sub, getKey(snapshot), snapshot.val());241 onData(FB_CHILD_ADDED, snapshot, sub);242 }, errorHandler);243 subscribedRegistry[sub.subKey].refHandles.child_changed = ref.on('child_changed', function(snapshot) {244 if (!gotInitVal) return;245 if (!check('child_changed', sub)) return;246 //Since we pass snapshot.val() to childSubs, it might use it, so we need call it when snapshot.val()247 //changes248 var childUnsub = subscribedRegistry[sub.subKey].childUnsubs[getKey(snapshot)];249 subscribeToChildData(sub, getKey(snapshot), snapshot.val());250 if (childUnsub) childUnsub();251 onData(FB_CHILD_WILL_CHANGE, snapshot, sub);252 onData(FB_CHILD_CHANGED, snapshot, sub);253 }, errorHandler);254 subscribedRegistry[sub.subKey].refHandles.child_removed = ref.on('child_removed', function(snapshot) {255 if (!gotInitVal) return;256 if (!check('child_removed', sub)) return;257 const childUnsub = subscribedRegistry[sub.subKey].childUnsubs[getKey(snapshot)];258 delete subscribedRegistry[sub.subKey].childUnsubs[getKey(snapshot)];259 if (childUnsub) childUnsub();260 onData(FB_CHILD_WILL_REMOVE, snapshot, sub);261 onData(FB_CHILD_REMOVED, snapshot, sub);262 }, errorHandler);263 ref.once('value', function(snapshot) {264 if (gotInitVal) {265 console.error("Got 'once' callback for "+getKey(snapshot)+" more than once");266 return;267 }268 gotInitVal = true;269 //We might've gotten unsubscribed while waiting for initial value, so check if we're still subscribed270 if (subscribedRegistry[sub.subKey]) {271 var val = snapshot.val();272 let nestedPromises = [];273 if (val !== null && (typeof val == 'object')) {274 Object.keys(val).forEach(childKey=>subscribeToChildData(sub, childKey, val[childKey], nestedPromises));275 }276 onData(FB_INIT_VAL, snapshot, sub);277 if (!subscribedRegistry[sub.subKey]) {278 //no longer subscribed (onData callback could've unsubscribed us)279 return;280 }281 //Once all initial child & field promises are resolved, we can resolve ourselves282 Promise.all(nestedPromises).then(() => {283 thePromise.resolve(sub.subKey);284 }, (error) => {285 thePromise.reject(error);286 });287 }288 }, errorHandler);289 }290 function executeValueSubscribeAction(sub : Sub, parentSubKey) {291 if (subscribedRegistry[sub.subKey]) {292 //Already subscribed, just increment ref count293 subscribedRegistry[sub.subKey].refCount++;294 if (parentSubKey) {295 const parentSubKeys = subscribedRegistry[sub.subKey].parentSubKeys;296 if (!parentSubKeys[parentSubKey]) {297 parentSubKeys[parentSubKey] = 1;298 } else {299 parentSubKeys[parentSubKey]++;300 }301 }302 //Check whether this subKey has itself in the parent chain, and if so, reject the promise303 if (!doNotDetectCycles) {304 detectAndReportSubscribeCycle(sub.subKey);305 }306 return;307 }308 var ref = resolveFirebaseQuery(sub);309 subscribedRegistry[sub.subKey] = {310 sub: sub,311 refCount: 1,312 ref: ref,313 parentSubKeys: {},314 childUnsubs: {},315 fieldUnsubs: {},316 refHandles: {}317 };318 if (parentSubKey) {319 subscribedRegistry[sub.subKey].parentSubKeys[parentSubKey] = 1;320 }321 loadedPromise(sub.subKey);322 const thePromise = promisesBySubKey[sub.subKey];323 let resolved = false;324 const errorHandler = handleFbError(sub);325 subscribedRegistry[sub.subKey].refHandles.value = ref.on('value', function(snapshot) {326 if (!check('value', sub)) return;327 //First subscribe to new value's nodes, then unsubscribe old ones - the ones in both old/new will remain328 //subscribed to firebase to avoid possibly blowing away firebase cache329 const oldChildUnsubs = Object.assign({}, subscribedRegistry[sub.subKey].childUnsubs);330 subscribedRegistry[sub.subKey].childUnsubs = {};331 const nestedPromises = (resolved ? null : []);332 var val = snapshot.val();333 if (val !== null && (typeof val == 'object')) {334 Object.keys(val).forEach(childKey=>subscribeToChildData(sub, childKey, val[childKey], nestedPromises));335 }336 Object.keys(oldChildUnsubs || {}).forEach(childKey=>{337 const childUnsub = oldChildUnsubs[childKey];338 childUnsub();339 });340 subscribeToFields(sub, val, nestedPromises);341 onData(FB_VALUE, snapshot, sub);342 if (!resolved) {343 resolved = true;344 if (!subscribedRegistry[sub.subKey]) {345 //no longer subscribed (onData callback could've unsubscribed us)346 return;347 }348 //Once all initial child & field promises are resolved, we can resolve ourselves349 Promise.all(nestedPromises).then(() => {350 thePromise.resolve(sub.subKey);351 }, (error) => {352 thePromise.reject(error);353 });354 }355 }, errorHandler);356 }357 function unsubscribeSubKey(subKey, parentSubKey?) {358 // if (disallowSubscriptions) {359 // reportError("Not allowed to unsubscribe within onSubscribed/onWillSubscribe/onUnsubscribed/onWillUnsubscribe callbacks");360 // return false;361 // }362 var info = subscribedRegistry[subKey];363 if (!info) {364 console.error('no subscriber found for subKey=' + subKey);365 } else {366 // disallowSubscriptions = true;367 if (onWillUnsubscribe) onWillUnsubscribe(subKey);368 // disallowSubscriptions = false;369 info.refCount--;370 if (parentSubKey) {371 if (info.parentSubKeys[parentSubKey] && info.parentSubKeys[parentSubKey] > 0) {372 info.parentSubKeys[parentSubKey]--;373 if (info.parentSubKeys[parentSubKey] <= 0){374 delete info.parentSubKeys[parentSubKey];375 }376 }377 }378 if (info.refCount <= 0) {379 delete subscribedRegistry[subKey];380 delete promisesBySubKey[subKey];381 Object.keys(info.refHandles).forEach(eventType=> {382 info.ref.off(eventType, info.refHandles[eventType]);383 });384 Object.keys(info.childUnsubs || {}).forEach(childKey=> {385 const childUnsub = info.childUnsubs[childKey];386 childUnsub();387 });388 Object.keys(info.fieldUnsubs || {}).forEach(fieldKey=> {389 const fieldUnsub = info.fieldUnsubs[fieldKey];390 fieldUnsub();391 });392 }393 }394 // disallowSubscriptions = true;395 if (onUnsubscribed) onUnsubscribed(subKey);396 // disallowSubscriptions = false;397 }398 function detectSubscribeCycle(subKey, parentSubKeys, trail, checked) {399 if (!parentSubKeys || parentSubKeys.length == 0) return false;400 let index = (parentSubKeys || []).indexOf(subKey);401 if (index >= 0) {402 return [...trail, parentSubKeys[index]];403 }404 const found = parentSubKeys.some(parentSubKey => {405 if (checked[parentSubKey]) return false;406 checked[parentSubKey] = true;407 const res = detectSubscribeCycle(subKey,408 Object.keys((subscribedRegistry[parentSubKey] || {}).parentSubKeys || {}),409 [...trail, parentSubKey], checked);410 if (res) {411 trail = res;412 return true;413 }414 return false;415 });416 return found ? trail : false;417 }418 function subscribeSub(sub : Sub, parentSubKey=rootSubKey) {419 // if (disallowSubscriptions) {420 // reportError("Not allowed to subscribe within onSubscribed/onWillSubscribe/onUnsubscribed/onWillUnsubscribe callbacks");421 // return () => false;422 // }423 if (!sub.subKey) {424 console.error('subscribeSub needs an object with a string subKey field');425 console.error(sub);426 return;427 }428 if (!sub.asList && !sub.asValue) {429 console.error('subscribeSub needs an object with either asList=true or asValue=true');430 console.error(sub);431 return;432 }433 // disallowSubscriptions = true;434 if (onWillSubscribe) onWillSubscribe(sub);435 // disallowSubscriptions = false;436 if (sub.asList) {437 executeListSubscribeAction(sub, parentSubKey);438 } else if (sub.asValue) {439 executeValueSubscribeAction(sub, parentSubKey);440 } else {441 console.error('sub must have asList or asValue = true');442 }443 // disallowSubscriptions = true;444 if (onSubscribed) onSubscribed(sub);445 // disallowSubscriptions = false;446 return function unsubscribe() {447 unsubscribeSubKey(sub.subKey, parentSubKey);448 }449 }450 function subscribeSubs(subs : Array<Sub>, parentSubKey=rootSubKey) {451 if (!subs) return;452 if (!subs.forEach) {453 console.error('subscribeSubs expects an array of subs');454 console.error(subs);455 return;456 }457 var unsubs = subs.map(sub=>subscribeSub(sub, parentSubKey));458 return function unsubscribe() {459 unsubs.forEach(unsub=>unsub());460 }461 }462 function subscribeSubsWithPromise(subs : Array<Sub>, parentSubKey=rootSubKey) {463 if (!subs) return;464 if (!subs.forEach) {465 console.error('subscribeSubs expects an array of subs');466 console.error(subs);467 return;468 }469 var unsubs = subs.map(sub =>subscribeSub(sub, parentSubKey));470 return {471 unsubscribe: function () {472 unsubs.forEach(unsub=>unsub());473 },474 promise: subsLoaded(subs)475 };476 }477 function unsubscribeAll() {478 for (let subKey in subscribedRegistry) {479 const sub = subscribedRegistry[subKey];480 const numRootSubscribes = (sub.parentSubKeys || {})[rootSubKey] || 0;481 for (let i = 0; i < numRootSubscribes; i++) {482 unsubscribeSubKey(subKey);483 }484 }485 }486 return { subscribeSubs, subscribedRegistry, unsubscribeAll, subscribeSubsWithPromise, loadedPromise };...

Full Screen

Full Screen

permissions.js

Source:permissions.js Github

copy

Full Screen

1import qs from 'qs';2import axiosInstanceWithCredentials from './util/axiosInstanceWithCredentials';3// import axiosWithCrendetials_cancelable from './util/axiosCancelWithCredentials';4function composeUrl({resource, key, subType, subKey, query = {}}) {5 query.checkPermissionsOnly = true;6 let str = `/${resource}`;7 if (typeof key !== 'undefined') {8 str += `/${key}`;9 if (typeof subType !== 'undefined') {10 str += `/${subType}`;11 if (typeof subKey !== 'undefined') {12 str += `/${subKey}`;13 }14 }15 }16 str += `?${qs.stringify(query)}`;17 return str;18}19const mayPost = ({resource, key, subType, subKey, query}) => {20 const url = composeUrl({resource, key, subType, subKey, query});21 return axiosInstanceWithCredentials.post(url, {})22 .then(() => true).catch(err => false);23};24const mayPut = ({resource, key, subType, subKey}) => {25 const url = composeUrl({resource, key, subType, subKey});26 return axiosInstanceWithCredentials.put(url, {})27 .then(() => true).catch(err => false);28};29const mayDelete = ({resource, key, subType, subKey}) => {30 const url = composeUrl({resource, key, subType, subKey});31 return axiosInstanceWithCredentials.delete(url)32 .then(() => true).catch(err => false);33};34const mayGet = ({resource, key, subType, subKey}) => {35 const url = composeUrl({resource, key, subType, subKey});36 return axiosInstanceWithCredentials.get(url)37 .then(() => true).catch(err => false);38};39export const checkPermissions = ({method, resource, key, subType, subKey}) => {40 if (method === 'post') return mayPost({resource, key, subType, subKey});41 if (method === 'put') return mayPut({resource, key, subType, subKey});42 if (method === 'delete') return mayDelete({resource, key, subType, subKey});43 return mayGet({resource, key, subType, subKey});44};45export const canCreate = (resource, key, subType, subKey, query) => {46 return mayPost({resource, key, subType, subKey, query});47}48export const canUpdate = (resource, key, subType, subKey) => {49 return mayPut({resource, key, subType, subKey});50}51export const canDelete = (resource, key, subType, subKey) => {52 return mayDelete({resource, key, subType, subKey});53}54export const canGet = (resource, key, subType, subKey) => {55 return mayGet({resource, key, subType, subKey});56}57//contacts58export const canCreateContact = (resource, key) => {59 return mayPost({resource, key, subType: 'contact'});60}61export const canUpdateContact = (resource, key, subKey) => {62 return mayPut({resource, key, subType: 'contact', subKey});63}64export const canDeleteContact = (resource, key, subKey) => {65 return mayDelete({resource, key, subType: 'contact', subKey});66}67export const canGetContact = (resource, key, subKey) => {68 return mayDelete({resource, key, subType: 'contact', subKey});69}70//endpoints71export const canCreateEndpoint = (resource, key) => {72 return mayPost({resource, key, subType: 'endpoint'});73}74export const canUpdateEndpoint = (resource, key, subKey) => {75 return mayPut({resource, key, subType: 'endpoint', subKey});76}77export const canDeleteEndpoint = (resource, key, subKey) => {78 return mayDelete({resource, key, subType: 'endpoint', subKey});79}80export const canGetEndpoint = (resource, key, subKey) => {81 return mayDelete({resource, key, subType: 'endpoint', subKey});82}83//identifier84export const canCreateIdentifier = (resource, key) => {85 return mayPost({resource, key, subType: 'identifier'});86}87export const canUpdateIdentifier = (resource, key, subKey) => {88 return mayPut({resource, key, subType: 'identifier', subKey});89}90export const canDeleteIdentifier = (resource, key, subKey) => {91 return mayDelete({resource, key, subType: 'identifier', subKey});92}93export const canGetIdentifier = (resource, key, subKey) => {94 return mayDelete({resource, key, subType: 'identifier', subKey});95}96//tags97export const canCreateTag = (resource, key) => {98 return mayPost({resource, key, subType: 'tag'});99}100export const canUpdateTag = (resource, key, subKey) => {101 return mayPut({resource, key, subType: 'tag', subKey});102}103export const canDeleteTag = (resource, key, subKey) => {104 return mayDelete({resource, key, subType: 'tag', subKey});105}106export const canGetTag = (resource, key, subKey) => {107 return mayDelete({resource, key, subType: 'tag', subKey});108}109//machineTags110export const canCreateMachineTag = (resource, key) => {111 return mayPost({resource, key, subType: 'machineTag'});112}113export const canUpdateMachineTag = (resource, key, subKey) => {114 return mayPut({resource, key, subType: 'machineTag', subKey});115}116export const canDeleteMachineTag = (resource, key, subKey) => {117 return mayDelete({resource, key, subType: 'machineTag', subKey});118}119export const canGetMachineTag = (resource, key, subKey) => {120 return mayDelete({resource, key, subType: 'machineTag', subKey});121}122//comments123export const canCreateComment = (resource, key) => {124 return mayPost({resource, key, subType: 'comment'});125}126export const canUpdateComment = (resource, key, subKey) => {127 return mayPut({resource, key, subType: 'comment', subKey});128}129export const canDeleteComment = (resource, key, subKey) => {130 return mayDelete({resource, key, subType: 'comment', subKey});131}132export const canGetComment = (resource, key, subKey) => {133 return mayDelete({resource, key, subType: 'comment', subKey});...

Full Screen

Full Screen

random.js

Source:random.js Github

copy

Full Screen

1const random = require('random-seed')2const rand = random.create('hello')3// 10 possible key characters.4const STRING_CHARS = 'abcdefghij'.split('')5const SUBKEY_LEN = 36const SUBKEY_PARTS = 57const SUBKEY_SEPARATOR = '/'8module.exports = {9 data: opts => {10 opts = makeDefault(opts)11 let data = new Array(opts.numKeys)12 for (let i = 0; i < opts.numKeys; i++) {13 let key = randomString(opts.subkeyParts, opts.subkeyLength, opts.subkeySeparator)14 data[i] = {15 type: 'put',16 key: key,17 value: rand.string(opts.valueSize),18 schema: 'doc', // for kappa19 id: key // for kappa20 }21 }22 return data23 },24 string: randomString25};26function randomString(subkeyParts, subkeyLength = SUBKEY_LEN, subkeySeparator = SUBKEY_SEPARATOR) {27 let string = ''28 for (let j = 0; j < subkeyParts; j++) {29 if (string.length) string += subkeySeparator30 for (let i = 0; i < subkeyLength; i++) {31 string += STRING_CHARS[rand.intBetween(0, STRING_CHARS.length - 1)]32 }33 }34 return string35}36function makeDefault(opts) {37 return Object.assign({38 valueSize: 10,39 subkeyLength: SUBKEY_LEN,40 subkeyParts: SUBKEY_PARTS,41 subkeySeparator: SUBKEY_SEPARATOR,42 numKeys: 1e343 }, opts)...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require("request");2var fs = require("fs");3var async = require("async");4var cheerio = require("cheerio");5var json2csv = require('json2csv');6var json2csv = require('json2csv');7var fields = ['name', 'salePrice', 'shortDescription', 'manufacturer', 'customerReviewAverage', 'customerReviewCount', 'url', 'image'];8var myCars = [];9request(url, function(error, response, body) {10 if (!error) {11 var bbObj = JSON.parse(body);12 var bbData = bbObj.products;13 for (var i = 0; i < bbData.length; i++) {14 var obj = bbData[i];15 var name = obj.name;16 var salePrice = obj.salePrice;17 var shortDescription = obj.shortDescription;18 var manufacturer = obj.manufacturer;19 var customerReviewAverage = obj.customerReviewAverage;20 var customerReviewCount = obj.customerReviewCount;21 var url = obj.url;22 var image = obj.image;23 myCars.push({

Full Screen

Using AI Code Generation

copy

Full Screen

1var BestCrypt = require('./BestCrypt.js');2var bc = new BestCrypt();3bc.subKey("test3.txt", "test.key", "test4.txt");4console.log("Decrypted text: " + bc.getDecryptedText());5console.log("Decrypted text: " + bc.getDecryptedText());6console.log("Decrypted text: " + bc.getDecryptedText());7console.log("Decrypted text: " + bc.getDecryptedText());8console.log("Decrypted text: " + bc.getDecryptedText());

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Component } from 'react';2import axios from 'axios';3import BestBuy from './BestBuy.js';4import Product from './Product.js';5import './App.css';6class App extends Component {7 constructor() {8 super();9 this.state = {10 }11 }12 handleSearch = (e) => {13 this.setState({14 });15 }16 handleSubmit = (e) => {17 e.preventDefault();18 this.setState({19 });20 const bestbuy = new BestBuy();21 bestbuy.subKey(this.state.search)22 .then(res => {23 const products = res.data.products;24 this.setState({25 });26 })27 .catch(err => {28 console.log(err);29 this.setState({30 });31 });32 }33 render() {34 const products = this.state.products;35 const loading = this.state.loading;36 let productList;37 if (products.length > 0) {38 productList = products.map(product => {39 return <Product key={product.sku} product={product} />40 });41 } else {42 }43 return (44 <form onSubmit={this.handleSubmit}>45 <input type="text" value={this.state.search} onChange={this.handleSearch}

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