Best JavaScript code snippet using wpt
type.ts
Source:type.ts  
1import { capitalize } from '../utils';2import { Schema } from 'mongoose';3import { t, objectTypeApi, enumTypeApi, interfaceTypeApi, inputTypeApi, unionTypeApi, TypeDefinitonApi } from 'graphql-extra';4import { resolvers } from 'graphql-scalars';5import { GraphQLScalarType, NamedTypeNode, DocumentNode } from "graphql";6import { ISpecificTypeInfo, IMongqlMongooseSchemaFull, IMongqlGeneratedTypes, AuthEnumString, InputActionEnumString, MutableDocumentNode, FieldsFullInfos, FieldFullInfo, MongqlSchemaConfigsFull, MongqlFieldAttachObjectConfigsFull, MongqlFieldPath, TParsedSchemaInfo, TSchemaInfos } from "../types";7import Password from "../utils/gql-types/password";8import Username from "../utils/gql-types/username";9import { generateNestedSchemaConfigs, generateFieldConfigs } from "../utils/generate/configs";10import { calculateFieldDepth } from "../utils/mongoose";11const Validators: { [key: string]: GraphQLScalarType["serialize"] } = {12  Password: Password.serialize,13  Username: Username.serialize14};15Object.entries({ ...resolvers }).forEach(([key, value]) => {16  Validators[key] = value.serialize;17});18function snakeCapitalize(type: string): string {19  return type.split('_').map(c => capitalize(c)).join(' ');20}21/**22 * Adds graphql nullable and list information to the type23 * @param type The type to decorate24 * @param reference reference array for decorating with list and null25 * @returns Decorated type26 */27function decorateTypes(type: string, reference: boolean[]) {28  let currentNested = 0;29  while (currentNested < reference.length - 1) {30    type = `[${type}${!reference[currentNested] ? '!' : ''}]`;31    currentNested++;32  }33  type = `${type}${!reference[currentNested] ? '!' : ''}`34  return type;35}36/**37 * Generate the generic type for the field38 * @param value Mongoose Field to parse39 * @returns The generated type generic type of the field 40 */41function generateGenericType(value: any): string {42  let generic_type = 'mongoose';43  const instanceOfSchema = value instanceof Schema || Object.getPrototypeOf(value).instanceOfSchema;44  if (instanceOfSchema) generic_type = 'object';45  else if (value.enum) generic_type = 'enum';46  else if (value.ref) generic_type = 'ref';47  else if (value.mongql?.scalar) generic_type = 'scalar';48  return generic_type;49}50/**51 * Parses and returns the Mongoose field GQL scalar type52 * 1. Checks mongql.scalar `name: {mongql:{scalar: PositiveInt}}`53 * 2. Checks type.name `name: {type:String} }`54 * 3. Field.name `name: String`55 * @param mongooseField Mongoose field to parse56 * @returns parsed scalar type57 */58function parseScalarType(mongooseField: any): string {59  const scalar = mongooseField.mongql?.scalar;60  let type = mongooseField.type;61  while (Array.isArray(type))62    type = type[0];63  if (scalar)64    type = scalar;65  else if (type) type = type.name;66  else type = mongooseField.name;67  if (type.match(/(Int32|Number)/)) type = 'Int';68  else if (type === 'Double') type = 'Float';69  if (type === 'ObjectId') type = 'ID';70  return type;71}72/**73 * Generate object, input and ref type without adding nullable or List syntax74 * @param generic_type generic_type of the field75 * @param value Mongoose field to generate type from76 * @param key The name of the field77 * @param parentKey The name of the parent of the field78 * @param resource Capitalized Resource name79 * @returns Generated type from a field80 */81function generateSpecificType(generic_type: string, value: any, key: string, parentKey: MongqlFieldPath, resource: string): ISpecificTypeInfo {82  let object_type = '',83    input_type = null,84    ref_type = null,85    enum_type = null;86  if (generic_type.match(/(object|enum)/)) {87    object_type = (parentKey ? parentKey.object_type : capitalize(resource)) + capitalize(value.mongql?.type || key);88    input_type = object_type + 'Input'89  }90  if (generic_type === 'enum') {91    object_type = (parentKey ? parentKey.object_type : capitalize(resource)) + capitalize(value.mongql?.type || key) + "Enum";92    enum_type = object_type;93    input_type = object_type;94  }95  else if (generic_type.match('ref')) {96    object_type = value.ref;97    input_type = `ID`;98    ref_type = value.ref;99  } else if (generic_type.match(/(scalar|mongoose)/))100    object_type = parseScalarType(value);101  input_type = input_type ? input_type : object_type;102  return { object_type, input_type, ref_type, enum_type };103}104const generateIncludedAuthSegments = (schema_object_auth: any, parentSchema_object_auth: string[] | any): [AuthEnumString[], AuthEnumString[]] => {105  const filterTrueKey = (obj: MongqlFieldAttachObjectConfigsFull) => Object.entries(obj).filter((entry) => entry[1]).map(([key]) => key);106  const parentSchema_auth_segments = Array.isArray(parentSchema_object_auth) ? parentSchema_object_auth : filterTrueKey(parentSchema_object_auth);107  const included_auth_segments = filterTrueKey(schema_object_auth).filter((auth) => parentSchema_auth_segments.includes(auth));108  const excluded_auth_segments = ['self', 'others', 'mixed'].filter(auth => !included_auth_segments.includes(auth));109  return [excluded_auth_segments as AuthEnumString[], included_auth_segments as AuthEnumString[]]110}111/**112 * Parse the MongooseSchema and populate the Graphql AST113 * @param BaseSchema Mongoose Schema to parse114 * @param InitTypedefsAST initial documentnode to add to 115 * @return Generated GraphqlDocumentNode and SchemaInfo116 */117function parseMongooseSchema(BaseSchema: IMongqlMongooseSchemaFull, InitTypedefsAST: DocumentNode | undefined) {118  const BaseSchemaConfigs = BaseSchema.mongql;119  const cr = capitalize(BaseSchemaConfigs.resource);120  const ResultDocumentNode = {121    kind: 'Document',122    definitions: InitTypedefsAST?.definitions ? [...InitTypedefsAST.definitions] : []123  };124  const Fields: FieldsFullInfos = [];125  const Types: IMongqlGeneratedTypes = {126    enums: [],127    unions: [],128    interfaces: [],129    objects: [],130    inputs: [],131  };132  const Schemas: TSchemaInfos = []133  function hasFields(AST: any): boolean {134    return (AST.fields || AST.values || AST.types).length > 0;135  }136  function _inner(Schema: IMongqlMongooseSchemaFull, Type: string, path: MongqlFieldPath[], ParentSchemaConfigs: MongqlSchemaConfigsFull) {137    const parentKey = path[path.length - 1];138    const CurrentSchemaConfigs = parentKey ? generateNestedSchemaConfigs(Schema.mongql || {}, ParentSchemaConfigs) : BaseSchemaConfigs;139    const [, currentSchema_included_auth_segments] = generateIncludedAuthSegments(CurrentSchemaConfigs.generate.type.object, ParentSchemaConfigs.generate.type.object);140    Object.values(Types).forEach(type => {141      type.push({})142    });143    const Interfaces = Types.interfaces[path.length];144    const Enums = Types.enums[path.length];145    const Objects = Types.objects[path.length];146    const Inputs = Types.inputs[path.length];147    const Unions = Types.unions[path.length];148    if (!Schemas[path.length]) Schemas.push({});149    const CurrentSchema = Schemas[path.length];150    CurrentSchema[Type] = { ...CurrentSchemaConfigs, fields: {} };151    const UnionsObjTypes: NamedTypeNode[] = [];152    currentSchema_included_auth_segments.forEach((auth) => {153      const ObjectName = `${capitalize(auth)}${Type}Object`;154      Objects[ObjectName] = Object.assign({}, objectTypeApi(155        t.objectType({156          name: ObjectName,157          description: `${capitalize(auth)} ${Type} Object Layer ${path.length + 1}`,158          fields: [],159          interfaces: CurrentSchemaConfigs.generate.type.interface ? [`${Type}Interface`] : []160        })161      ), { fields: {} });162      UnionsObjTypes.push({163        kind: 'NamedType',164        name: {165          kind: 'Name',166          value: ObjectName167        }168      })169    });170    Unions[`${Type}Union`] = unionTypeApi(171      t.unionType({172        name: `${Type}Union`,173        description: `${Type} Union Layer ${path.length + 1}`,174        types: UnionsObjTypes175      })176    );177    ['Create', 'Update'].forEach(action => {178      Inputs[`${action}${Type}Input`] = inputTypeApi(179        t.inputType({180          name: `${action}${Type}Input`,181          description: `${action} ${Type} Input Layer ${path.length + 1}`,182          fields: []183        })184      );185      if (action === 'Update' && !parentKey) Inputs[`${action}${Type}Input`].createField({ name: 'id', type: 'ID!' });186    })187    Interfaces[`${Type}Interface`] = interfaceTypeApi(188      t.interfaceType({189        name: `${Type}Interface`,190        description: `${Type} Interface Layer ${path.length + 1}`,191        fields: []192      })193    );194    if (!Fields[path.length]) Fields.push({});195    Object.entries(Schema.obj).forEach(([key, value]: [string, any]) => {196      const [fieldDepth, innerValue] = calculateFieldDepth(value);197      const generic_type = generateGenericType(innerValue) + (fieldDepth > 0 ? 's' : '');198      const generatedFieldConfigs = generateFieldConfigs(value, CurrentSchemaConfigs);199      const { description, authMapper, nullable: { input: nullable_input, object: nullable_object }, attach: { input: attach_to_input, interface: attach_to_interface, enum: attach_to_enum } } = generatedFieldConfigs;200      const { object_type, input_type, ref_type, enum_type } = generateSpecificType(generic_type, innerValue, key, parentKey, cr);201      const [field_excluded_auth_segments, field_included_auth_segments] = generateIncludedAuthSegments(generatedFieldConfigs.attach.object, currentSchema_included_auth_segments);202      path = parentKey ? [...path, { object_type, key, enum_type }] : [{ object_type, key, enum_type }];203      const generatedFieldFullInfo: FieldFullInfo = Object.assign({}, generatedFieldConfigs, {204        input_type,205        generic_type,206        ref_type,207        object_type,208        excludedAuthSegments: field_excluded_auth_segments,209        includedAuthSegments: field_included_auth_segments,210        fieldDepth,211        enum_type,212        path: [...path],213        decorated_types: {214          object: {},215          input: {}216        }217      })218      Fields[path.length - 1][key] = generatedFieldFullInfo;219      CurrentSchema[Type].fields[key] = generatedFieldFullInfo;220      if (generic_type.match(/(scalar)/))221        BaseSchema.path(path.map(({ key }) => key).join('.')).validate((v: any) => {222          const value = Validators[object_type](v);223          return value !== null && value !== undefined;224        }, ((props: any) => props.reason.message) as any);225      field_included_auth_segments.forEach((auth) => {226        path[path.length - 1] = { object_type, key, enum_type };227        const auth_object_type = generic_type.match(/(ref|object)/)228          ? authMapper[capitalize(auth) as AuthEnumString] + object_type + "Object"229          : object_type;230        const decorated_object_type = decorateTypes(auth_object_type, nullable_object[auth]);231        generatedFieldFullInfo.decorated_types.object[auth] = decorated_object_type;232        const object_key = `${capitalize(auth)}${Type}Object`;233        if (!Objects[object_key].hasField(key)) {234          Objects[object_key].fields[key] = { ...generatedFieldFullInfo, auth };235          Objects[object_key].createField({236            name: key, description, type: decorated_object_type237          });238        }239      });240      ['create', 'update'].forEach((action) => {241        const _action = capitalize(action);242        if (CurrentSchemaConfigs.generate.type.input[action as InputActionEnumString] && attach_to_input[action as InputActionEnumString] && !Inputs[`${_action}${Type}Input`].hasField(key)) {243          const decorated_input_type = decorateTypes((generic_type.match(/(object)/) ? _action : "") + input_type, nullable_input[action as InputActionEnumString])244          generatedFieldFullInfo.decorated_types.input[action as InputActionEnumString] = decorated_input_type;245          Inputs[`${_action}${Type}Input`].createField({ name: key, type: decorated_input_type });246        }247      })248      if (CurrentSchemaConfigs.generate.type.enum && attach_to_enum && generic_type.match(/(enum)/))249        Enums[object_type] = enumTypeApi(t.enumType({250          name: object_type,251          description: snakeCapitalize(`${parentKey ? parentKey.object_type : Type}_${key}_enum`),252          values: [...value.enum]253        }));254      if (CurrentSchemaConfigs.generate.type.interface && (field_excluded_auth_segments.length !== 2 && field_included_auth_segments.length !== 2) && field_included_auth_segments.length !== 0 && attach_to_interface && !Interfaces[`${Type}Interface`].hasField(key))255        Interfaces[`${Type}Interface`].createField({256          name: key, type: decorateTypes(object_type + (generic_type.match(/(ref|object)/) ? "Union" : ""), nullable_object[(field_included_auth_segments)[0]])257        })258      if (generic_type.match(/(object)/))259        _inner(innerValue, object_type, path, CurrentSchemaConfigs);260      path.pop();261      // if (value.mongql) delete value.mongql;262    });263    // if (Schema.mongql && parentKey)264    //   delete Schema.mongql265  }266  _inner(BaseSchema, cr, [], BaseSchemaConfigs);267  ['Self', 'Others', 'Mixed'].forEach(auth => {268    Types.objects[0][`${auth}${cr}PaginationObject`] = Object.assign({},269      objectTypeApi(270        t.objectType({271          name: `${auth}${cr}PaginationObject`,272          description: `${auth} ${cr} Pagination Object`,273          fields: [],274          interfaces: []275        })276      ), { fields: {} });277    Types.objects[0][`${auth}${cr}PaginationObject`].createField({ name: 'count', type: 'PositiveInt!' });278    Types.objects[0][`${auth}${cr}PaginationObject`].createField({ name: 'pagination', type: 'PaginationObject!' });279    Types.objects[0][`${auth}${cr}PaginationObject`].createField({ name: 'data', type: `[${auth}${cr}Object!]!` });280  })281  Object.values(Types).forEach((types) => {282    types.forEach((type: TypeDefinitonApi) => {283      Object.values(type).forEach((value) => {284        if (hasFields(value.node)) ResultDocumentNode.definitions.push(value.node || value);285      });286    })287  });288  const SchemaInfo: TParsedSchemaInfo = {289    Types,290    Fields,291    Schemas,292    Operations: []293  };294  return {295    DocumentAST: ResultDocumentNode as MutableDocumentNode,296    SchemaInfo297  };298}299export {300  parseMongooseSchema,301  decorateTypes,302  generateGenericType,303  parseScalarType,304  generateSpecificType...index.js
Source:index.js  
1const LIBRARIES = {2  Skill: require("../../../Libraries/Skill"),3  Axios: require("axios")4};5class Jeedom extends LIBRARIES.Skill {6  constructor(_main, _settings) {7    super(_main, _settings);8    const SELF = this;9    SELF.Main.Manager.addAction("Jeedom.on", function(_intent, _socket){10      SELF.Action("on", _intent, _socket);11    });12    SELF.Main.Manager.addAction("Jeedom.off", function(_intent, _socket){13      SELF.Action("off", _intent, _socket);14    });15    SELF.Main.Manager.addAction("Jeedom.open", function(_intent, _socket){16      SELF.Action("open", _intent, _socket);17    });18    SELF.Main.Manager.addAction("Jeedom.close", function(_intent, _socket){19      SELF.Action("close", _intent, _socket);20    });21  }22  Action(_code, _intent, _socket){23    _code = " " + _code + " ";24    const SELF = this;25    if(_intent.Variables.zone == undefined){26      _intent.Variables.zone = "";27    }28    SELF.Main.HTTPSJsonGet(SELF.Settings.jeedomIP, "/core/api/jeeApi.php?apikey=" + SELF.Settings.jeedomToken + "&type=fullData", function(rooms){29      if(rooms != null){30        for(const roomIndex in rooms){31          const ROOM = rooms[roomIndex];32          ROOM.name = " " + (ROOM.name == null ? "" : ROOM.name.toLowerCase()) + " ";33          ROOM.name = ROOM.name.replace("-", " ");34          if(ROOM.name.includes(" " + _intent.Variables.zone.toLowerCase() + " ")){35            for(const objectIndex in ROOM.eqLogics){36              const OBJECT = ROOM.eqLogics[objectIndex];37              if(OBJECT.name.toLowerCase().includes(_intent.Variables.target.toLowerCase())){38                for(const cmdIndex in OBJECT.cmds){39                  const CMD = OBJECT.cmds[cmdIndex];40                  CMD.name = " " + (CMD.name == null ? "" : CMD.name.toLowerCase()) + " ";41                  CMD.generic_type = " " + (CMD.generic_type == null ? "" : CMD.generic_type.toLowerCase()) + " ";42                  CMD.name = CMD.name.replace("_", " ");43                  CMD.generic_type = CMD.generic_type.replace("_", " ");44                  CMD.name = CMD.name.replace("-", " ");45                  CMD.generic_type = CMD.generic_type.replace("-", " ");46                  if(CMD.name.includes(_code) || CMD.generic_type.includes(_code)){47                    SELF.Main.HTTPSJsonGet(SELF.Settings.jeedomIP, "/core/api/jeeApi.php?apikey=" + SELF.Settings.jeedomToken + "&type=cmd&id=" + CMD.id);48                  }49                }50              }51            }52          }53        }54      }55      else{56        SELF.Main.Log("Error", "red");57      }58    }, false);59  }60}...generic.ts
Source:generic.ts  
1import SystemId from 'system/enum/id';2import NodeParameters from 'type/node-parameters';3import SystemNodeBuilder from 'system/node-builder';4class GenericTypeBuilder extends SystemNodeBuilder {5	protected getNodeParameters(): NodeParameters {6		return {7			type_id: SystemId.GENERIC_TYPE,8			id: SystemId.GENERIC_TYPE9		};10	}11	protected getPermissionUrls(): string[] {12		const urls = super.getPermissionUrls();13		const admin_create_url = this.buildUrl(14			SystemId.PERMISSION_TYPE,15			SystemId.ADMIN_CREATE_PERMISSION16		);17		return [...urls, admin_create_url];18	}19	protected getInstanceUrls(): string[] {20		return [21			this.buildUrl(SystemId.GENERIC_TYPE, SystemId.ACCOUNT_TYPE),22			this.buildUrl(SystemId.GENERIC_TYPE, SystemId.CHANGE_TYPE),23			this.buildUrl(SystemId.GENERIC_TYPE, SystemId.GROUP_TYPE),24			this.buildUrl(SystemId.GENERIC_TYPE, SystemId.PERMISSION_TYPE),25			this.buildUrl(SystemId.GENERIC_TYPE, SystemId.SESSION_TYPE),26			this.buildUrl(SystemId.GENERIC_TYPE, SystemId.STRING_TYPE)27		];28	}29}...Using AI Code Generation
1var request = require('request');2var wptools = require('wptools');3var fs = require('fs');4var page = wptools.page('Barack Obama');5page.get(function(err, resp) {6  console.log(resp);7});Using AI Code Generation
1const wptools = require('wptools');2const fs = require('fs');3const data = fs.readFileSync('data.json');4const dataJSON = JSON.parse(data);5const keys = Object.keys(dataJSON);6const values = Object.values(dataJSON);7const map = new Map();8let count = 0;9let count2 = 0;10for (let i = 0; i < keys.length; i++) {11        .page(keys[i])12        .then((page) => {13            return page.generic_type();14        })15        .then((generic_type) => {16            console.log(generic_type);17            map.set(keys[i], generic_type);18            count++;19            if (count == keys.length) {20                const json = JSON.stringify(map);21                fs.writeFile('generic_type.json', json, 'utf8', () => {});22            }23        })24        .catch((err) => {25            console.log('error');26            map.set(keys[i], err);27            count2++;28            if (count2 == keys.length) {29                const json = JSON.stringify(map);30                fs.writeFile('generic_type.json', json, 'utf8', () => {});31            }32        });33}34const wptools = require('wptools');35const fs = require('fs');36const data = fs.readFileSync('data.json');37const dataJSON = JSON.parse(data);38const keys = Object.keys(dataJSON);39const values = Object.values(dataJSON);40const map = new Map();41let count = 0;42let count2 = 0;43for (let i = 0; i < keys.length; i++) {44        .page(keys[i])45        .then((page) => {46            return page.infobox();47        })48        .then((infobox) => {49            console.log(infobox);50            map.set(keys[i], infobox);51            count++;52            if (count == keys.length) {53                const json = JSON.stringify(map);54                fs.writeFile('infobox.json', json, 'utf8', () => {});55            }56        })57        .catch((err) => {58            console.log('error');59            map.set(keys[i], err);60            count2++;61            if (count2 == keys.length) {62                const json = JSON.stringify(map);63                fs.writeFile('infobox.json', json, 'Using AI Code Generation
1var wptools = require('wptools');2var wp = wptools.page('Barack Obama');3wp.get(function(err, info) {4    console.log(info);5});6var wptools = require('wptools');7var wp = wptools.page('Barack Obama');8wp.get(function(err, info) {9    console.log(info.infobox);10});11var wptools = require('wptools');12var wp = wptools.page('Barack Obama');13wp.get(function(err, info) {14    console.log(info.infobox);15});16var wptools = require('wptools');17var wp = wptools.page('Barack Obama');18wp.get(function(err, info) {19    console.log(info.infobox);20});21var wptools = require('wptools');22var wp = wptools.page('Barack Obama');23wp.get(function(err, info) {24    console.log(info.infobox);25});26var wptools = require('wptools');27var wp = wptools.page('Barack Obama');28wp.get(function(err, info) {29    console.log(info.infobox);30});31var wptools = require('wptools');32var wp = wptools.page('Barack Obama');33wp.get(function(err, info) {34    console.log(info.infobox);35});Using AI Code Generation
1var wpt = require('webpagetest');2var options = {3};4var wpt = new WebPageTest('www.webpagetest.org', options);5}, function(err, data) {6    if (err) return console.error(err);7    console.log('Test status:', data.statusText);8    wpt.getTestStatus(data.data.testId, function(err, data) {9        if (err) return console.error(err);10        console.log('Test status:', data.statusText);11    });12});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!!
