Best JavaScript code snippet using redwood
execute-hooks.test.ts
Source:execute-hooks.test.ts
1import {2 Hook,3 HookExecutor,4 HookInput,5 HookOutput,6 HooksExecutionOutput,7 InternalStacksContext,8 Stack,9 StackOperationVariables,10} from "@takomo/stacks-model"11import { createConsoleLogger } from "@takomo/util"12import { mock } from "jest-mock-extended"13import { executeHooks } from "../src"14class ThrowingHook implements Hook {15 private readonly error: Error16 executed = false17 constructor(error: Error) {18 this.error = error19 }20 execute = async (): Promise<HookOutput> => {21 this.executed = true22 throw this.error23 }24}25class TestHook implements Hook {26 private readonly output: HookOutput27 executed = false28 constructor(output: HookOutput) {29 this.output = output30 }31 execute = async (): Promise<HookOutput> => {32 this.executed = true33 return this.output34 }35}36class SkipHook implements Hook {37 executed = false38 execute = async (): Promise<HookOutput> => {39 this.executed = true40 return {41 skip: true,42 success: true,43 }44 }45}46class HandlerHook implements Hook {47 private readonly handler: (input: HookInput) => Promise<HookOutput>48 executed = false49 constructor(handler: (input: HookInput) => Promise<HookOutput>) {50 this.handler = handler51 }52 execute = async (input: HookInput): Promise<HookOutput> => {53 this.executed = true54 return this.handler(input)55 }56}57const ctx: InternalStacksContext = mock<InternalStacksContext>()58const createVariables = (): StackOperationVariables => ({59 context: { projectDir: "" },60 env: {},61 var: {},62 hooks: {},63})64const logger = createConsoleLogger({65 logLevel: "info",66})67const executor = (name: string, hook: Hook): HookExecutor =>68 new HookExecutor(69 {70 name,71 type: "cmd",72 },73 hook,74 )75const stack = mock<Stack>()76const executeAllHooks = async (77 variables: StackOperationVariables,78 ...executors: HookExecutor[]79): Promise<HooksExecutionOutput> =>80 executeHooks({81 ctx,82 stack,83 variables,84 logger,85 hooks: executors,86 operation: "create",87 stage: "before",88 })89describe("#executeHooks", () => {90 describe("when no hooks are given", () => {91 test("returns success", async () => {92 const result = await executeHooks({93 ctx,94 stack,95 logger,96 variables: createVariables(),97 hooks: [],98 operation: "create",99 stage: "before",100 })101 expect(result).toStrictEqual({102 result: "continue",103 message: "Success",104 })105 })106 })107 describe("when a single hook that executes successfully is given", () => {108 test("returns success", async () => {109 const hook1 = new TestHook(true)110 const hook1Executor = new HookExecutor(111 {112 name: "mock1",113 type: "cmd",114 },115 hook1,116 )117 const result = await executeHooks({118 ctx,119 stack,120 logger,121 variables: createVariables(),122 hooks: [hook1Executor],123 operation: "create",124 stage: "before",125 })126 expect(result).toStrictEqual({127 result: "continue",128 message: "Success",129 })130 expect(hook1.executed).toBeTruthy()131 })132 })133 describe("when a single hook that throws an exception is given", () => {134 test("returns error", async () => {135 const hook1 = new ThrowingHook(new Error("Error error!"))136 const hook1Executor = new HookExecutor(137 {138 name: "mock1",139 type: "cmd",140 },141 hook1,142 )143 const result = await executeHooks({144 ctx,145 stack,146 logger,147 variables: createVariables(),148 hooks: [hook1Executor],149 operation: "create",150 stage: "before",151 })152 expect(result).toStrictEqual({153 result: "abort",154 message: "Error error!",155 error: undefined,156 })157 expect(hook1.executed).toBe(true)158 })159 })160 describe("when multiple hooks are given", () => {161 test("executes only the hooks that match with the given operation, stage and status", async () => {162 const hook1 = new TestHook(true)163 const hook1Executor = new HookExecutor(164 {165 operation: ["create"],166 stage: ["before"],167 name: "mock1",168 type: "cmd",169 },170 hook1,171 )172 const hook2 = new TestHook(true)173 const hook2Executor = new HookExecutor(174 {175 operation: ["delete"],176 stage: ["after"],177 name: "mock2",178 type: "cmd",179 },180 hook2,181 )182 const hook3 = new TestHook(true)183 const hook3Executor = new HookExecutor(184 {185 name: "mock3",186 type: "cmd",187 },188 hook3,189 )190 const result = await executeHooks({191 ctx,192 stack,193 logger,194 variables: createVariables(),195 hooks: [hook1Executor, hook2Executor, hook3Executor],196 operation: "delete",197 stage: "after",198 })199 expect(result).toStrictEqual({200 result: "continue",201 message: "Success",202 })203 expect(hook1.executed).toBeFalsy()204 expect(hook2.executed).toBeTruthy()205 expect(hook3.executed).toBeTruthy()206 })207 })208 describe("when a hook fails", () => {209 test("the remaining hooks are not executed", async () => {210 const hook1 = new TestHook({ success: true, value: "A" })211 const hook2 = new TestHook({ success: false, value: "B" })212 const hook3 = new TestHook({ success: true, value: "C" })213 const hook4 = new TestHook({ success: true, value: "D" })214 const hook1Executor = new HookExecutor(215 {216 name: "mock1",217 type: "cmd",218 },219 hook1,220 )221 const hook2Executor = new HookExecutor(222 {223 name: "mock2",224 type: "cmd",225 },226 hook2,227 )228 const hook3Executor = new HookExecutor(229 {230 name: "mock3",231 type: "cmd",232 },233 hook3,234 )235 const hook4Executor = new HookExecutor(236 {237 name: "mock4",238 type: "cmd",239 },240 hook4,241 )242 const variables = createVariables()243 const result = await executeHooks({244 ctx,245 stack,246 variables,247 hooks: [hook1Executor, hook2Executor, hook3Executor, hook4Executor],248 operation: "delete",249 stage: "after",250 logger,251 })252 expect(result.result).toStrictEqual("abort")253 expect(hook1.executed).toBeTruthy()254 expect(hook2.executed).toBeTruthy()255 expect(hook3.executed).toBeFalsy()256 expect(hook4.executed).toBeFalsy()257 expect(variables.hooks).toStrictEqual({258 mock1: "A",259 mock2: "B",260 })261 })262 })263 describe("when a hook returns skip", () => {264 test("the remaining hooks are not executed", async () => {265 const hook1 = new TestHook({ success: true, value: "A" })266 const hook2 = new SkipHook()267 const hook3 = new TestHook({ success: true, value: "C" })268 const hook4 = new TestHook({ success: true, value: "D" })269 const hook1Executor = new HookExecutor(270 {271 name: "mock1",272 type: "cmd",273 },274 hook1,275 )276 const hook2Executor = new HookExecutor(277 {278 name: "mock2",279 type: "cmd",280 },281 hook2,282 )283 const hook3Executor = new HookExecutor(284 {285 name: "mock3",286 type: "cmd",287 },288 hook3,289 )290 const hook4Executor = new HookExecutor(291 {292 name: "mock4",293 type: "cmd",294 },295 hook4,296 )297 const variables = createVariables()298 const result = await executeHooks({299 ctx,300 stack,301 variables,302 hooks: [hook1Executor, hook2Executor, hook3Executor, hook4Executor],303 operation: "create",304 stage: "before",305 logger,306 })307 expect(result.result).toStrictEqual("skip")308 expect(hook1.executed).toBeTruthy()309 expect(hook2.executed).toBeTruthy()310 expect(hook3.executed).toBeFalsy()311 expect(hook4.executed).toBeFalsy()312 expect(variables.hooks).toStrictEqual({313 mock1: "A",314 mock2: undefined,315 })316 })317 })318 describe("returned value should be correct", () => {319 test("when a hook returns primitive false", async () => {320 const hook = new TestHook(false)321 const variables = createVariables()322 const result = await executeAllHooks(variables, executor("hook1", hook))323 expect(result.result).toStrictEqual("abort")324 expect(result.message).toBe("Failed")325 expect(variables.hooks["hook1"]).toBe(false)326 })327 test("when a hook returns primitive true", async () => {328 const hook = new TestHook(true)329 const variables = createVariables()330 const result = await executeAllHooks(variables, executor("hook2", hook))331 expect(result.result).toStrictEqual("continue")332 expect(result.message).toBe("Success")333 expect(variables.hooks["hook2"]).toBe(true)334 })335 test("when a hook returns an error object", async () => {336 const err = new Error("My error")337 const hook = new TestHook(err)338 const variables = createVariables()339 const result = await executeAllHooks(variables, executor("hook3", hook))340 expect(result.result).toStrictEqual("abort")341 expect(result.message).toBe("My error")342 expect(variables.hooks["hook3"]).toBe(err)343 })344 test("when a hook returns an output object", async () => {345 const hook = new TestHook({ success: true, value: "X", message: "OK" })346 const variables = createVariables()347 const result = await executeAllHooks(variables, executor("hook4", hook))348 expect(result.result).toStrictEqual("continue")349 expect(result.message).toBe("Success")350 expect(variables.hooks["hook4"]).toBe("X")351 })352 })353 describe("when multiple hooks are executed", () => {354 test("subsequent hooks should be able to see output values of prior hooks", async () => {355 const hook1 = new TestHook({ success: true, value: "Hello XXXX!" })356 const hook2 = new TestHook({ success: true, value: "Frodo" })357 const hook3 = new HandlerHook((input: HookInput): Promise<HookOutput> => {358 const greeting = input.variables.hooks["hook1"]359 const name = input.variables.hooks["hook2"]360 const value = greeting.replace("XXXX", name)361 return Promise.resolve({ success: true, value })362 })363 const variables = createVariables()364 await executeAllHooks(365 variables,366 executor("hook1", hook1),367 executor("hook2", hook2),368 executor("hook3", hook3),369 )370 expect(variables.hooks["hook3"]).toBe("Hello Frodo!")371 })372 })...
useIssues.js
Source:useIssues.js
1import { useState } from "react";2import { useQuery } from "@apollo/client";3import { login } from "../../../api/userData";4import { GET_REPOSITORY_ISSUES } from "../../../api/queries";5export const useIssues = (repo) => {6 const sizeOptions = [5, 10, 15, 20, 100];7 const [onPage, setOnPage] = useState(sizeOptions[0]);8 const createVariables = (first, after, last, before) => ({9 login: login,10 repo: repo,11 first: first,12 after: after,13 last: last,14 before: before,15 });16 const { loading, error, data, refetch } = useQuery(GET_REPOSITORY_ISSUES, {17 variables: createVariables(onPage, null, null, null),18 });19 const goPrevPage = () => {20 const { startCursor } = data.repository.issues.pageInfo;21 refetch(createVariables(null, null, onPage, startCursor));22 };23 const goNextPage = () => {24 const { endCursor } = data.repository.issues.pageInfo;25 refetch(createVariables(onPage, endCursor, null, null));26 };27 const handleSizeChange = (e) => {28 setOnPage(parseInt(e.target.value));29 };30 return {31 loading,32 error,33 data,34 goPrevPage,35 onPage,36 handleSizeChange,37 sizeOptions,38 goNextPage,39 };...
index.js
Source:index.js
1#!/usr/bin/env node2const inquirer = require('inquirer');3const { hexToHSL, RGBToHSL } = require('./converter');4const createVariables = require('./createVariables');5const colors = require('colors');6inquirer7 .prompt([8 {9 type : 'rawlist',10 choices : [11 'RGB',12 'HEX',13 'HSL'14 ],15 name : 'type',16 message : 'Choose a format for giving input color to generate variables'17 },18 {19 type : 'input',20 name : 'color',21 message :22 'Enter a color in choosen format e.g RGB like rgb(r,g,b) or HEX Code like #aa23a4 or HSL like hsl(330,100%,50%)'23 },24 {25 type : 'input',26 name : 'variable',27 message : 'Enter a variable name'28 }29 ])30 .then((answers) => {31 const { type, color, variable } = answers;32 if (type == 'RGB') {33 createVariables(RGBToHSL(color), variable);34 }35 else if (type == 'HEX') {36 createVariables(hexToHSL(color), variable);37 }38 else {39 createVariables(color, variable);40 }41 })42 .catch((error) => {43 console.log(colors.red.bold(error));...
Using AI Code Generation
1var redwoodService = require('redwood-service');2var data = {3 {4 },5 {6 }7};8service.CreateVariables(data, function (error, response) {9 if (error) {10 console.log(error);11 } else {12 console.log(response);13 }14});15var redwoodService = require('redwood-service');16var data = {17};18service.GetVariables(data, function (error, response) {19 if (error) {20 console.log(error);21 } else {22 console.log(response);23 }24});25var redwoodService = require('redwood-service');26var data = {27 {28 },29 {30 }31};32service.UpdateVariables(data, function (error, response) {33 if (error) {34 console.log(error);35 } else {36 console.log(response);37 }38});39var redwoodService = require('redwood-service');40var data = {41};42service.DeleteVariables(data, function (error, response) {43 if (error) {44 console.log(error);45 } else {46 console.log(response);47 }48});49var redwoodService = require('redwood-service');
Using AI Code Generation
1var redwood = require('redwoodjs');2var redwoodClient = new redwood.RedwoodClient('localhost', 8080);3var redwoodSession = redwoodClient.createSession();4var redwoodSessionId = redwoodSession.getSessionId();5var redwoodSessionToken = redwoodSession.getSessionToken();6var createVariableRequest = new redwood.CreateVariablesRequest();7createVariableRequest.setSessionId(redwoodSessionId);8createVariableRequest.setSessionToken(redwoodSessionToken);9var variable = new redwood.Variable();10variable.setName('var1');11variable.setValue('value1');12createVariableRequest.addVariable(variable);13var variable2 = new redwood.Variable();14variable2.setName('var2');15variable2.setValue('value2');16createVariableRequest.addVariable(variable2);17redwoodSession.createVariables(createVariableRequest, function(err, response) {18 if (err) {19 console.log(err);20 } else {21 console.log(response);22 }23});
Using AI Code Generation
1var redwood = require('redwood');2var redwoodVariables = redwood.CreateVariables();3var redwoodVariable = redwoodVariables.CreateVariable("test");4redwoodVariable.SetValue(10);5console.log(redwoodVariable.GetValue());6var redwood = require('redwood');7var redwoodVariables = redwood.CreateVariables();8var redwoodVariable = redwoodVariables.CreateVariable("test");9console.log(redwoodVariable.GetValue());
Using AI Code Generation
1redwood.createVariables("test", 10, "test2", 20, "test3", 30);2var testValue = redwood.getVariableValue("test");3var test2Value = redwood.getVariableValue("test2");4var test3Value = redwood.getVariableValue("test3");5redwood.setVariableValue("test", 100);6redwood.setVariableValue("test2", 200);7redwood.setVariableValue("test3", 300);8redwood.setVariableValue("test4", 400);9var testValue = redwood.getVariableValue("test");10var test2Value = redwood.getVariableValue("test2");11var test3Value = redwood.getVariableValue("test3");12var test4Value = redwood.getVariableValue("test4");13redwood.deleteVariable("test");
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!!