Best JavaScript code snippet using wpt
user-service.ts
Source:user-service.ts
1import { UserModel } from '../models/user-model'2import { User } from '../data/models'3import { UserRegisterInputModel } from '../models/user-input-models'4import { Repository } from '../data/repositories'5import { TaskResult } from '../common/taskResult'6import { Roles } from '../common'7import { ObjectId } from 'mongodb'8import { QueryArgsHelper } from '../utils/query-args-helper'9import { CompanyColumns, UserColumns } from '../data/models/user-columns'10import { AvailabilityModel } from '../models/availability-model'11import { DAYS_OF_WEEK, TIME_CONSTANTS, WORKING_TIME } from '../common/application-constants'12import { ObjectExtensions } from '../utils/object-extensions'13import { ModelBuilders } from '../utils/model-builders'14import { TimeHelper } from '../utils/time-helper'15const jwt = require('jsonwebtoken')16const bcrypt = require('bcrypt')17class UserService {18 private usersData: Repository<UserModel>19 public constructor (usersData: Repository<UserModel>) {20 this.usersData = usersData21 }22 public async register (user: UserRegisterInputModel): Promise<UserModel | null> {23 if (await User.findOne({ email: user.email })) {24 return null25 }26 const salt = await bcrypt.genSalt(10)27 const userToCreate = { ...user }28 userToCreate.password = await bcrypt.hash(user.password, salt)29 const createdUser: UserModel = await User.create(userToCreate)30 return createdUser31 }32 public async login (email: string, password: string) {33 const user = await this.usersData.firstOrDefault({ email })34 if (user && await bcrypt.compare(password, user.password)) {35 const userData = {36 id: user.id,37 email: user.email,38 roles: user.roles39 }40 const accessToken: string = jwt.sign(userData, process.env.TOKEN_SECRET, { expiresIn: '1h' })41 return {42 userData: {43 ...userData,44 firstName: user.firstName,45 lastName: user.lastName,46 phone: user.phone47 },48 accessToken49 }50 }51 return null52 }53 public async getProfileData (userId: string): Promise<any> {54 const projection = QueryArgsHelper.build(55 QueryArgsHelper.disable(UserColumns.password),56 QueryArgsHelper.disable(UserColumns.favourites)57 )58 return this.usersData.getById(userId, projection)59 }60 public async getFavouritesBusinesses (userId: string): Promise<any> {61 const { favourites } = await this.usersData.getById(userId)62 const projection = QueryArgsHelper.build(63 UserColumns.id,64 UserColumns.firstName,65 UserColumns.lastName,66 QueryArgsHelper.combine(UserColumns.company, CompanyColumns.description),67 QueryArgsHelper.combine(UserColumns.company, CompanyColumns.address),68 QueryArgsHelper.combine(UserColumns.company, CompanyColumns.businessType)69 )70 const filter = {71 _id: {72 $in: [...favourites]73 }74 }75 filter[QueryArgsHelper.combine(UserColumns.company, CompanyColumns.businessType)] = {76 $ne: undefined77 }78 const businesses = await this.usersData.filter(filter, projection, {79 populate: QueryArgsHelper.combine(UserColumns.company, CompanyColumns.businessType)80 })81 return businesses82 }83 public async addToFavourites (userId: string, businessId: string): Promise<TaskResult> {84 const user: UserModel = await this.usersData.getById(userId)85 if (!user) {86 return TaskResult.failure('The user does not exist.')87 }88 if (user.favourites.some(id => id.toString() === businessId)) {89 return TaskResult.failure('The passed business is already added to favourites.')90 }91 if (!await this.usersData.exists({92 _id: businessId,93 roles: Roles.businessHolder94 })) {95 return TaskResult.failure('The chosen business is not valid.')96 }97 user.favourites.push(new ObjectId(businessId))98 await this.usersData.update(userId, { favourites: [...user.favourites] })99 return TaskResult.success('Added to favourites.')100 }101 public async removeFromFavourites (userId: string, businessId: string): Promise<TaskResult> {102 const user: UserModel = await this.usersData.getById(userId)103 if (!user) {104 return TaskResult.failure('The user does not exist.')105 }106 if (user.favourites.length === 0 || user.favourites.every(id => id.toString() !== businessId)) {107 return TaskResult.failure('The passed business is not added to favourites.')108 }109 if (!await this.usersData.exists({110 _id: businessId,111 roles: Roles.businessHolder112 })) {113 return TaskResult.failure('The chosen business is not valid.')114 }115 user.favourites = user.favourites.filter(userId => userId.toString() !== businessId)116 await this.usersData.update(userId, { favourites: [...user.favourites] })117 return TaskResult.success('Removed from favourites.')118 }119 public setBusinessType (userId: string, businessType: string): Promise<TaskResult> {120 const updatedFields = {121 [QueryArgsHelper.combine(UserColumns.company, CompanyColumns.businessType)]: businessType122 }123 return this.usersData.update(userId, updatedFields)124 .then(() => TaskResult.success('The user business type is updated.'))125 .catch(() => TaskResult.failure('Error while updating the business type.'))126 }127 public setAvailability (userId: string, availability: AvailabilityModel[]): Promise<TaskResult> {128 const updatedFields = {129 [QueryArgsHelper.combine(UserColumns.company, CompanyColumns.availability)]: availability130 }131 return this.usersData.update(userId, updatedFields)132 .then(() => TaskResult.success('The user availability is updated.'))133 .catch(() => TaskResult.failure('Error while updating the availability.'))134 }135 public updatePersonalData (userId: string, personalData: { firstName: string; lastName: string; phone: string }): Promise<TaskResult> {136 return this.usersData.update(userId, personalData)137 .then(() => TaskResult.success('The user personal data is updated.'))138 .catch(() => TaskResult.failure('Error while updating the user personal data.'))139 }140 public buildDefaultAvailability (workingDays: number[]): AvailabilityModel[] {141 return workingDays.map(day => {142 return ModelBuilders.buildAvailability(WORKING_TIME.start, WORKING_TIME.end, day)143 })144 }145 public parseAvailability (availability: any): TaskResult<AvailabilityModel[]> {146 if (!Array.isArray(availability)) {147 return TaskResult.failure('The availability should be array.')148 }149 const parsedAvailability = []150 for (const element of availability) {151 if (!ObjectExtensions.isObject(element)) {152 return TaskResult.failure('Some of the element in the array are not objects.')153 }154 if (!(element.day && element.day >= DAYS_OF_WEEK.Monday && element.day <= DAYS_OF_WEEK.Sunday)) {155 return TaskResult.failure(`Invalid day. The day should be between: ${DAYS_OF_WEEK.Monday} and ${DAYS_OF_WEEK.Sunday}`)156 }157 if (!(element.startHour >= TIME_CONSTANTS.minHour && element.startHour <= TIME_CONSTANTS.maxHour)) {158 return TaskResult.failure(`Invalid start hour. The start hour should be between: ${TIME_CONSTANTS.minHour} and ${TIME_CONSTANTS.maxHour}`)159 }160 if (!(element.startMinute >= TIME_CONSTANTS.minMinute && element.startMinute <= TIME_CONSTANTS.maxMinute)) {161 return TaskResult.failure(`Invalid start minute. The start minute should be between: ${TIME_CONSTANTS.minMinute} and ${TIME_CONSTANTS.maxMinute}`)162 }163 if (!(element.endHour >= TIME_CONSTANTS.minHour && element.endHour <= TIME_CONSTANTS.maxHour)) {164 return TaskResult.failure(`Invalid end hour. The end hour should be between: ${TIME_CONSTANTS.minHour} and ${TIME_CONSTANTS.maxHour}`)165 }166 if (!(element.endMinute >= TIME_CONSTANTS.minMinute && element.endMinute <= TIME_CONSTANTS.maxMinute)) {167 return TaskResult.failure(`Invalid end minute. The end minute should be between: ${TIME_CONSTANTS.minMinute} and ${TIME_CONSTANTS.maxMinute}`)168 }169 const start = {170 hour: element.startHour,171 minute: element.startMinute172 }173 const end = {174 hour: element.endHour,175 minute: element.endMinute176 }177 if (TimeHelper.compare(start, end) > 0) {178 return TaskResult.failure('Start time cannot be less than or equal to end time')179 }180 parsedAvailability.push(ModelBuilders.buildAvailability(start, end, element.day))181 }182 return TaskResult.success('Availability is valid', parsedAvailability)183 }184}...
TaskRunner.js
Source:TaskRunner.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.default = void 0;6var _os = _interopRequireDefault(require("os"));7var _pLimit = _interopRequireDefault(require("p-limit"));8var _jestWorker = _interopRequireDefault(require("jest-worker"));9var _serializeJavascript = _interopRequireDefault(require("serialize-javascript"));10var _minify = _interopRequireDefault(require("./minify"));11function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }12const workerPath = require.resolve('./worker');13class TaskRunner {14 constructor(options = {}) {15 this.taskGenerator = options.taskGenerator;16 this.files = options.files;17 this.cache = options.cache;18 this.availableNumberOfCores = TaskRunner.getAvailableNumberOfCores(options.parallel);19 }20 static getAvailableNumberOfCores(parallel) {21 // In some cases cpus() returns undefined22 // https://github.com/nodejs/node/issues/1902223 const cpus = _os.default.cpus() || {24 length: 125 };26 return parallel === true ? cpus.length - 1 : Math.min(Number(parallel) || 0, cpus.length - 1);27 }28 async runTask(task) {29 if (this.worker) {30 return this.worker.transform((0, _serializeJavascript.default)(task));31 }32 return (0, _minify.default)(task);33 }34 async run() {35 const {36 availableNumberOfCores,37 cache,38 files,39 taskGenerator40 } = this;41 let concurrency = Infinity;42 if (availableNumberOfCores > 0) {43 // Do not create unnecessary workers when the number of files is less than the available cores, it saves memory44 const numWorkers = Math.min(files.length, availableNumberOfCores);45 concurrency = numWorkers;46 this.worker = new _jestWorker.default(workerPath, {47 numWorkers48 }); // https://github.com/facebook/jest/issues/8872#issuecomment-52482208149 const workerStdout = this.worker.getStdout();50 if (workerStdout) {51 workerStdout.on('data', chunk => {52 return process.stdout.write(chunk);53 });54 }55 const workerStderr = this.worker.getStderr();56 if (workerStderr) {57 workerStderr.on('data', chunk => {58 return process.stderr.write(chunk);59 });60 }61 }62 const limit = (0, _pLimit.default)(concurrency);63 const scheduledTasks = [];64 for (const file of files) {65 const enqueue = async task => {66 let taskResult;67 try {68 taskResult = await this.runTask(task);69 } catch (error) {70 taskResult = {71 error72 };73 }74 if (cache.isEnabled() && !taskResult.error) {75 taskResult = await cache.store(task, taskResult).then(() => taskResult, () => taskResult);76 }77 task.callback(taskResult);78 return taskResult;79 };80 scheduledTasks.push(limit(() => {81 const task = taskGenerator(file).next().value;82 if (!task) {83 // Something went wrong, for example the `cacheKeys` option throw an error84 return Promise.resolve();85 }86 if (cache.isEnabled()) {87 return cache.get(task).then(taskResult => task.callback(taskResult), () => enqueue(task));88 }89 return enqueue(task);90 }));91 }92 return Promise.all(scheduledTasks);93 }94 async exit() {95 if (!this.worker) {96 return Promise.resolve();97 }98 return this.worker.end();99 }100}...
takeover.ts
Source:takeover.ts
1import { Reason, TaskResult } from "Task";2export function takeoverRoom(creep: Creep, controller: StructureController): TaskResult {3 if (creep.store.getUsedCapacity() === 0)4 return new TaskResult(controller.my, Reason.NO_ENERGY);5 if (controller.my) {6 const result = creep.upgradeController(controller);7 switch (result) {8 case OK:9 return new TaskResult(creep.store.getUsedCapacity() === 0, creep.store.getUsedCapacity() === 0 ? Reason.COMPLETED : Reason.IN_PROGRESS);10 case ERR_NOT_OWNER:11 return new TaskResult(false, Reason.INVALID_TARGET);12 case ERR_NOT_ENOUGH_ENERGY:13 return new TaskResult(false, Reason.NO_ENERGY);14 case ERR_NO_BODYPART:15 return new TaskResult(false, Reason.INVALID_TARGET);16 case ERR_NOT_IN_RANGE:17 creep.moveTo(controller, { visualizePathStyle: { stroke: "#00ffff" } });18 return new TaskResult(false, Reason.NOT_IN_RANGE);19 }20 } else if (creep.getActiveBodyparts(CLAIM) === 0) {21 return new TaskResult(false, Reason.INVALID_TARGET);22 }23 if (controller.level === 0) {24 const result = creep.claimController(controller);25 switch (result) {26 case OK:27 return new TaskResult(true, Reason.COMPLETED);28 case ERR_NOT_OWNER:29 case ERR_INVALID_TARGET:30 creep.attackController(controller);31 return new TaskResult(true, Reason.COMPLETED);32 case ERR_NOT_IN_RANGE:33 creep.moveTo(controller, { visualizePathStyle: { stroke: "#ff3300" } });34 return new TaskResult(false, Reason.NOT_IN_RANGE);35 case ERR_GCL_NOT_ENOUGH:36 creep.reserveController(controller);37 return new TaskResult(true, Reason.COMPLETED);38 }39 } else {40 if (creep.attackController(controller) === ERR_NOT_IN_RANGE)41 creep.moveTo(controller);42 }43 return new TaskResult(false, Reason.NONE);...
Using AI Code Generation
1wpt.taskResult(taskId, function(err, data) {2 console.log(data);3});4wpt.getLocations(function(err, data) {5 console.log(data);6});7wpt.getTesters(function(err, data) {8 console.log(data);9});10wpt.getRuns(function(err, data) {11 console.log(data);12});13wpt.getRun(runId, function(err, data) {14 console.log(data);15});16wpt.getRunPagespeed(runId, function(err, data) {17 console.log(data);18});19wpt.getRunPageSpeedSummary(runId, function(err, data) {20 console.log(data);21});22wpt.getRunPageSpeedBreakdown(runId, function(err, data) {23 console.log(data);24});25wpt.getRunPageSpeedTimeline(runId, function(err, data) {26 console.log(data);27});28wpt.getRunPageSpeedHistogram(runId, function(err, data) {29 console.log(data);30});31wpt.getRunPageSpeedScreenshot(runId, function(err, data) {32 console.log(data);33});34wpt.getRunPageSpeedUserTimings(runId, function(err, data) {35 console.log(data);36});37wpt.getRunPageSpeedPageStats(runId
Using AI Code Generation
1var wpt = require('webpagetest');2var webpagetest = new wpt('www.webpagetest.org');3webpagetest.runTest(url, function(err, data) {4 if (err) {5 console.log(err);6 } else {7 webpagetest.getTestResults(data.data.testId, function(err, data) {8 if (err) {9 console.log(err);10 } else {11 console.log(data);12 }13 });14 }15});16[MIT](
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.runTest(url, {4}, function(err, data) {5 if (err) {6 console.log(err);7 } else {8 console.log(data);9 }10});
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new wpt('Wpt API Key');3wpt.runTest(testurl, function(err, data) {4 if (err) {5 console.log(err);6 }7 else {8 console.log(data);9 wpt.taskResult(data.data.testId, function(err, data) {10 if (err) {11 console.log(err);12 }13 else {14 console.log(data);15 }16 });17 }18});
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.taskResult('141207_5Q_17a2f7c8a8d8e7f1e6b1c1e8d6a9c7d0', function(err, data) {4 console.log(data);5});6var wpt = require('webpagetest');7var wpt = new WebPageTest('www.webpagetest.org');8 console.log(data);9});10var wpt = require('webpagetest');11var wpt = new WebPageTest('www.webpagetest.org');12 console.log(data);13});14var wpt = require('webpagetest');15var wpt = new WebPageTest('www.webpagetest.org');16wpt.getTestResults('141207_5Q_17a2f7c8a8d8e7f1e6b1c1e8d6a9c7d0', function(err, data) {17 console.log(data);18});19var wpt = require('webpagetest');20var wpt = new WebPageTest('www.webpagetest.org');21wpt.getTestResults('141207_5Q_17a2f7c8a8d8e7f1e6b1c1e8d6a9c7d0', { requests: 1 }, function(err, data) {22 console.log(data);23});
Using AI Code Generation
1var wpt = require('webpagetest');2var client = wpt('A.7f0c6d2b7b3c0a1f6c1d3e3f9e9f6b0b');3 if (err) return console.error(err);4 client.getTestResults(data.data.testId, function(err, data) {5 if (err) return console.error(err);6 console.log(data.data);7 });8});9var wpt = require('webpagetest');10var client = wpt('A.7f0c6d2b7b3c0a1f6c1d3e3f9e9f6b0b');11 if (err) return console.error(err);12 client.getTestResults(data.data.testId, function(err, data) {13 if (err) return console.error(err);14 console.log(data.data);15 });16});17var wpt = require('webpagetest');18var client = wpt('A.7f0c6d2b7b3c0a1f6c1d3e3f9e9f6b0b');19 if (err) return console.error(err);20 client.getTestResults(data.data.testId, function(err, data) {21 if (err) return console.error(err);22 console.log(data.data);23 });24});
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!!