How to use currentStatus method in root

Best JavaScript code snippet using root

message-generation.ts

Source:message-generation.ts Github

copy

Full Screen

1import {2 APIInteractionResponse,3 APIModalSubmitGuildInteraction,4 InteractionResponseType,5 MessageFlags,6} from "discord-api-types/v9";7import { FastifyInstance } from "fastify";8import {9 ExpectedFailure,10 InteractionOrRequestFinalStatus,11 UnexpectedFailure,12} from "../../errors";13import {14 getMessageFromCache,15 MessageSavedInCache,16 saveMessageToCache,17} from "../../lib/messages/cache";18import { isIsoDate } from "../../lib/messages/embeds/utils";19import { GuildSession } from "../../lib/session";20import { InternalInteractionType } from "../interaction";21import {22 createEmbedMessageGenerationEmbed,23 createInitialMessageGenerationEmbed,24 MessageGenerationButtonTypes,25} from "../shared/message-generation";26import { InteractionReturnData } from "../types";27export default async function handleModalMessageGeneration(28 internalInteraction: InternalInteractionType<APIModalSubmitGuildInteraction>,29 session: GuildSession,30 instance: FastifyInstance31): Promise<InteractionReturnData> {32 const interaction = internalInteraction.interaction;33 const messageGenerationKey = interaction.data.custom_id.split(":")[1] as34 | string35 | undefined;36 const messageGenerationType = interaction.data.custom_id.split(":")[2] as37 | MessageGenerationButtonTypes38 | undefined;39 if (40 messageGenerationKey === undefined ||41 messageGenerationType === undefined42 ) {43 throw new UnexpectedFailure(44 InteractionOrRequestFinalStatus.COMPONENT_CUSTOM_ID_MALFORMED,45 "No message id on message generation button"46 );47 }48 const currentStatus = await getMessageFromCache({49 key: messageGenerationKey,50 instance,51 });52 switch (messageGenerationType) {53 case "content":54 return await handleContent({55 interaction,56 currentStatus,57 messageGenerationKey,58 instance,59 });60 case "embed-metadata":61 return await handleEmbedMetadata({62 interaction,63 currentStatus,64 messageGenerationKey,65 instance,66 });67 case "embed-footer":68 return await handleEmbedFooter({69 interaction,70 currentStatus,71 messageGenerationKey,72 instance,73 });74 case "embed-content":75 return await handleEmbedContent({76 interaction,77 currentStatus,78 messageGenerationKey,79 instance,80 });81 case "embed-add-field":82 return await handleEmbedAddField({83 interaction,84 currentStatus,85 messageGenerationKey,86 instance,87 });88 case "embed-author":89 return await handleEmbedAuthor({90 interaction,91 currentStatus,92 messageGenerationKey,93 instance,94 });95 case "edit-embed-field":96 return await handleEditEmbedField({97 interaction,98 currentStatus,99 messageGenerationKey,100 instance,101 });102 default:103 throw new UnexpectedFailure(104 InteractionOrRequestFinalStatus.MODAL_CUSTOM_ID_NOT_FOUND,105 "Invalid message generation type for modal"106 );107 }108}109const handleContent = async ({110 interaction,111 currentStatus,112 messageGenerationKey,113 instance,114}: {115 interaction: APIModalSubmitGuildInteraction;116 currentStatus: MessageSavedInCache;117 messageGenerationKey: string;118 instance: FastifyInstance;119}): Promise<APIInteractionResponse> => {120 const content = interaction.data.components?.find(121 (component) => component.components[0].custom_id === "content"122 )?.components[0].value;123 if (interaction.channel_id === undefined) {124 throw new UnexpectedFailure(125 InteractionOrRequestFinalStatus.GENERIC_UNEXPECTED_FAILURE,126 "Missing channel_id on modal submit"127 ); // Not sure why this might happen128 }129 currentStatus.content = content;130 await saveMessageToCache({131 key: messageGenerationKey,132 instance,133 data: currentStatus,134 });135 const responseData = createInitialMessageGenerationEmbed(136 messageGenerationKey,137 currentStatus,138 interaction.guild_id139 );140 return {141 type: InteractionResponseType.UpdateMessage,142 data: {143 embeds: [responseData.embed],144 components: responseData.components,145 flags: MessageFlags.Ephemeral,146 },147 };148};149const handleEmbedMetadata = async ({150 interaction,151 currentStatus,152 messageGenerationKey,153 instance,154}: {155 interaction: APIModalSubmitGuildInteraction;156 currentStatus: MessageSavedInCache;157 messageGenerationKey: string;158 instance: FastifyInstance;159}): Promise<APIInteractionResponse> => {160 const color = interaction.data.components?.find(161 (component) => component.components[0].custom_id === "color"162 )?.components[0].value;163 const timestamp = interaction.data.components?.find(164 (component) => component.components[0].custom_id === "timestamp"165 )?.components[0].value;166 const url = interaction.data.components?.find(167 (component) => component.components[0].custom_id === "url"168 )?.components[0].value;169 const thumbnailUrl = interaction.data.components?.find(170 (component) => component.components[0].custom_id === "thumbnail"171 )?.components[0].value;172 // If any are set, and embed is undefined define embed173 if (174 currentStatus.embed === undefined &&175 ((color !== undefined && color !== "") ||176 (timestamp !== undefined && timestamp !== "") ||177 (url !== undefined && url !== "") ||178 (thumbnailUrl !== undefined && thumbnailUrl !== ""))179 ) {180 currentStatus.embed = {};181 } else if (currentStatus.embed === undefined) {182 // None are set, and none have been set therefore we can safely return183 const returnData = createEmbedMessageGenerationEmbed(184 messageGenerationKey,185 currentStatus186 );187 return {188 type: InteractionResponseType.UpdateMessage,189 data: {190 embeds: [returnData.embed],191 components: returnData.components,192 flags: MessageFlags.Ephemeral,193 },194 };195 }196 // If color is set check if it a valid integer color197 if (color !== undefined && color !== "") {198 if (isNaN(Number(color))) {199 throw new ExpectedFailure(200 InteractionOrRequestFinalStatus.EMBED_VALUE_EDITING_MALFORMED,201 "Color is not a valid integer"202 );203 }204 currentStatus.embed.color = Number(color);205 } else {206 currentStatus.embed.color = undefined;207 }208 // If timestamp is set check if it a valid ISO8601 timestamp209 if (timestamp !== undefined && timestamp !== "") {210 if (!isIsoDate(timestamp)) {211 throw new ExpectedFailure(212 InteractionOrRequestFinalStatus.EMBED_VALUE_EDITING_MALFORMED,213 "Timestamp is not a valid ISO8601 timestamp"214 );215 }216 currentStatus.embed.timestamp = timestamp;217 } else {218 currentStatus.embed.timestamp = undefined;219 }220 // If url is set check if it a valid URL221 if (url !== undefined && url !== "") {222 if (!/^(http|https):\/\/[^ "]+$/.test(url)) {223 throw new ExpectedFailure(224 InteractionOrRequestFinalStatus.EMBED_VALUE_EDITING_MALFORMED,225 "URL is not a valid URL"226 );227 }228 currentStatus.embed.url = url;229 } else {230 currentStatus.embed.url = undefined;231 }232 // If thumbnailUrl is set check if it a valid URL233 if (thumbnailUrl !== undefined && thumbnailUrl !== "") {234 if (!/^(http|https):\/\/[^ "]+$/.test(thumbnailUrl)) {235 throw new ExpectedFailure(236 InteractionOrRequestFinalStatus.EMBED_VALUE_EDITING_MALFORMED,237 "Thumbnail URL is not a valid URL"238 );239 }240 currentStatus.embed.thumbnail = {241 url: thumbnailUrl,242 };243 } else {244 currentStatus.embed.thumbnail = undefined;245 }246 // Update the message in the cache247 await saveMessageToCache({248 key: messageGenerationKey,249 instance,250 data: currentStatus,251 });252 const returnData = createEmbedMessageGenerationEmbed(253 messageGenerationKey,254 currentStatus255 );256 return {257 type: InteractionResponseType.UpdateMessage,258 data: {259 embeds: [returnData.embed],260 components: returnData.components,261 flags: MessageFlags.Ephemeral,262 },263 };264};265const handleEmbedFooter = async ({266 interaction,267 currentStatus,268 messageGenerationKey,269 instance,270}: {271 interaction: APIModalSubmitGuildInteraction;272 currentStatus: MessageSavedInCache;273 messageGenerationKey: string;274 instance: FastifyInstance;275}): Promise<APIInteractionResponse> => {276 const text = interaction.data.components?.find(277 (component) => component.components[0].custom_id === "text"278 )?.components[0].value;279 const iconUrl = interaction.data.components?.find(280 (component) => component.components[0].custom_id === "icon"281 )?.components[0].value;282 if (283 (text !== undefined && text !== "") ||284 (iconUrl !== undefined && iconUrl !== "") ||285 (currentStatus.embed?.footer?.text !== undefined &&286 currentStatus.embed?.footer?.text !== "") ||287 (currentStatus.embed?.footer?.icon_url !== undefined &&288 currentStatus.embed?.footer?.icon_url !== "")289 // Only "edit" the embed if new values will be set, or they already have been set290 ) {291 if (currentStatus.embed === undefined) {292 currentStatus.embed = {};293 }294 console.log("a");295 if (296 (text === undefined || text === "") &&297 iconUrl !== undefined &&298 iconUrl !== ""299 ) {300 // Text must be set for footer, this means text not set icon set301 throw new ExpectedFailure(302 InteractionOrRequestFinalStatus.EMBED_EDITING_MISSING_REQUIRED_VALUE,303 "Footer text must be set for any other footer value to be set. Either set a footer text, or remove the icon url."304 );305 }306 if (text === undefined || text === "") {307 // Icon url must also be undefined due to above check308 currentStatus.embed.footer = undefined;309 console.log("b");310 } else {311 if (currentStatus.embed.footer === undefined) {312 currentStatus.embed.footer = { text };313 } else {314 currentStatus.embed.footer.text = text;315 }316 console.log("c");317 if (iconUrl !== undefined && iconUrl !== "") {318 // Validate iconurl is a valid url319 if (!/^(http|https):\/\/[^ "]+$/.test(iconUrl)) {320 throw new ExpectedFailure(321 InteractionOrRequestFinalStatus.EMBED_VALUE_EDITING_MALFORMED,322 "Icon URL is not a valid URL"323 );324 }325 currentStatus.embed.footer.icon_url = iconUrl;326 }327 }328 console.log("d");329 console.log(currentStatus.embed.footer);330 await saveMessageToCache({331 key: messageGenerationKey,332 instance,333 data: currentStatus,334 });335 }336 const returnData = createEmbedMessageGenerationEmbed(337 messageGenerationKey,338 currentStatus339 );340 return {341 type: InteractionResponseType.UpdateMessage,342 data: {343 embeds: [returnData.embed],344 components: returnData.components,345 flags: MessageFlags.Ephemeral,346 },347 };348};349const handleEmbedContent = async ({350 interaction,351 currentStatus,352 messageGenerationKey,353 instance,354}: {355 interaction: APIModalSubmitGuildInteraction;356 currentStatus: MessageSavedInCache;357 messageGenerationKey: string;358 instance: FastifyInstance;359}): Promise<APIInteractionResponse> => {360 const title = interaction.data.components?.find(361 (component) => component.components[0].custom_id === "title"362 )?.components[0].value;363 const description = interaction.data.components?.find(364 (component) => component.components[0].custom_id === "description"365 )?.components[0].value;366 if (367 (title !== undefined && title !== "") ||368 (description !== undefined && description !== "") ||369 (currentStatus.embed?.title !== undefined &&370 currentStatus.embed?.title !== "") ||371 (currentStatus.embed?.description !== undefined &&372 currentStatus.embed?.description !== "")373 ) {374 if (currentStatus.embed === undefined) {375 currentStatus.embed = {};376 }377 if (title !== undefined && title !== "") {378 currentStatus.embed.title = title;379 } else {380 currentStatus.embed.title = undefined;381 }382 if (description !== undefined && description !== "") {383 currentStatus.embed.description = description;384 } else {385 currentStatus.embed.description = undefined;386 }387 await saveMessageToCache({388 key: messageGenerationKey,389 instance,390 data: currentStatus,391 });392 }393 const returnData = createEmbedMessageGenerationEmbed(394 messageGenerationKey,395 currentStatus396 );397 return {398 type: InteractionResponseType.UpdateMessage,399 data: {400 embeds: [returnData.embed],401 components: returnData.components,402 flags: MessageFlags.Ephemeral,403 },404 };405};406const parseTrueLikeValues = (value: string | undefined): boolean => {407 // 'true' 't' 'y' 'yes' 'on' '1' - true408 // 'false' 'f' 'n' 'no' 'off' '0' and any other value - false409 // Case insensitive410 if (value === undefined) {411 return false;412 }413 const parsed = value.toLowerCase();414 return (415 parsed === "true" ||416 parsed === "t" ||417 parsed === "y" ||418 parsed === "yes" ||419 parsed === "on" ||420 parsed === "1"421 );422};423const handleEmbedAddField = async ({424 interaction,425 currentStatus,426 messageGenerationKey,427 instance,428}: {429 interaction: APIModalSubmitGuildInteraction;430 currentStatus: MessageSavedInCache;431 messageGenerationKey: string;432 instance: FastifyInstance;433}): Promise<APIInteractionResponse> => {434 const fieldName = interaction.data.components?.find(435 (component) => component.components[0].custom_id === "name"436 )?.components[0].value;437 const fieldValue = interaction.data.components?.find(438 (component) => component.components[0].custom_id === "value"439 )?.components[0].value;440 const inline = parseTrueLikeValues(441 interaction.data.components?.find(442 (component) => component.components[0].custom_id === "inline"443 )?.components[0].value444 );445 if (446 fieldName === undefined ||447 fieldName === "" ||448 fieldValue === undefined ||449 fieldValue === ""450 ) {451 // Name and value must be set, as this is adding a field452 throw new UnexpectedFailure(453 InteractionOrRequestFinalStatus.EMBED_EDITING_MISSING_DISCORD_REQUIRED_VALUE,454 "Field name and value must be set."455 );456 }457 if (currentStatus.embed === undefined) {458 currentStatus.embed = {};459 }460 if (currentStatus.embed.fields === undefined) {461 currentStatus.embed.fields = [];462 }463 currentStatus.embed.fields.push({464 name: fieldName,465 value: fieldValue,466 inline,467 });468 await saveMessageToCache({469 key: messageGenerationKey,470 instance,471 data: currentStatus,472 });473 const returnData = createEmbedMessageGenerationEmbed(474 messageGenerationKey,475 currentStatus476 );477 return {478 type: InteractionResponseType.UpdateMessage,479 data: {480 embeds: [returnData.embed],481 components: returnData.components,482 flags: MessageFlags.Ephemeral,483 },484 };485};486const handleEditEmbedField = async ({487 interaction,488 currentStatus,489 messageGenerationKey,490 instance,491}: {492 interaction: APIModalSubmitGuildInteraction;493 currentStatus: MessageSavedInCache;494 messageGenerationKey: string;495 instance: FastifyInstance;496}): Promise<APIInteractionResponse> => {497 const fieldName = interaction.data.components?.find(498 (component) => component.components[0].custom_id === "name"499 )?.components[0].value;500 const fieldValue = interaction.data.components?.find(501 (component) => component.components[0].custom_id === "value"502 )?.components[0].value;503 const inline = parseTrueLikeValues(504 interaction.data.components?.find(505 (component) => component.components[0].custom_id === "inline"506 )?.components[0].value507 );508 const fieldIndex = Number(interaction.data.custom_id.split(":")[3]);509 if (510 (fieldName === undefined || fieldName === "") &&511 (fieldValue === undefined || fieldValue === "")512 ) {513 // Clear the field if name or value is not set514 if (currentStatus.embed?.fields?.[fieldIndex] !== undefined) {515 currentStatus.embed.fields.splice(fieldIndex, 1);516 }517 } else {518 // Otherwise, update the field519 // Both name and value must be set520 if (521 fieldName === undefined ||522 fieldName === "" ||523 fieldValue === undefined ||524 fieldValue === ""525 ) {526 throw new UnexpectedFailure(527 InteractionOrRequestFinalStatus.EMBED_EDITING_MISSING_DISCORD_REQUIRED_VALUE,528 "Field name and value both must be set. To remove the field make sure both are empty."529 );530 }531 if (currentStatus.embed === undefined) {532 currentStatus.embed = {};533 }534 if (currentStatus.embed.fields === undefined) {535 currentStatus.embed.fields = [];536 }537 if (currentStatus.embed.fields[fieldIndex] === undefined) {538 currentStatus.embed.fields.push({539 name: fieldName,540 value: fieldValue,541 inline,542 });543 } else {544 currentStatus.embed.fields[fieldIndex] = {545 name: fieldName,546 value: fieldValue,547 inline,548 };549 }550 }551 await saveMessageToCache({552 key: messageGenerationKey,553 instance,554 data: currentStatus,555 });556 const returnData = createEmbedMessageGenerationEmbed(557 messageGenerationKey,558 currentStatus559 );560 return {561 type: InteractionResponseType.UpdateMessage,562 data: {563 embeds: [returnData.embed],564 components: returnData.components,565 flags: MessageFlags.Ephemeral,566 },567 };568};569const handleEmbedAuthor = async ({570 interaction,571 currentStatus,572 messageGenerationKey,573 instance,574}: {575 interaction: APIModalSubmitGuildInteraction;576 currentStatus: MessageSavedInCache;577 messageGenerationKey: string;578 instance: FastifyInstance;579}): Promise<APIInteractionResponse> => {580 // Handle author name, url, and icon url581 // Author name **must be set** if any values are set582 const authorName = interaction.data.components?.find(583 (component) => component.components[0].custom_id === "name"584 )?.components[0].value;585 const authorUrl = interaction.data.components?.find(586 (component) => component.components[0].custom_id === "url"587 )?.components[0].value;588 const authorIconUrl = interaction.data.components?.find(589 (component) => component.components[0].custom_id === "icon"590 )?.components[0].value;591 if (592 (authorName !== undefined && authorName !== "") ||593 (authorUrl !== undefined && authorUrl !== "") ||594 (authorIconUrl !== undefined && authorIconUrl !== "") ||595 currentStatus.embed?.author?.name !== undefined // Only need to check name, as it must be set if any other is set596 ) {597 if (authorName === undefined || authorName === "") {598 if (599 (authorUrl !== undefined && authorUrl !== "") ||600 (authorIconUrl !== undefined && authorIconUrl !== "")601 ) {602 throw new ExpectedFailure(603 InteractionOrRequestFinalStatus.EMBED_EDITING_MISSING_REQUIRED_VALUE,604 "Author name must be set for any other author value to be set. Either set an author name, or remove the author url or author icon url."605 );606 }607 if (currentStatus.embed !== undefined) {608 currentStatus.embed.author = undefined;609 }610 } else {611 if (currentStatus.embed === undefined) {612 currentStatus.embed = {};613 }614 if (currentStatus.embed.author === undefined) {615 currentStatus.embed.author = { name: authorName };616 } else {617 currentStatus.embed.author.name = authorName;618 }619 if (authorUrl !== undefined && authorUrl !== "") {620 // Validate authorurl is a valid url621 if (!/^(http|https):\/\/[^ "]+$/.test(authorUrl)) {622 throw new ExpectedFailure(623 InteractionOrRequestFinalStatus.EMBED_VALUE_EDITING_MALFORMED,624 "Author URL is not a valid URL"625 );626 }627 currentStatus.embed.author.url = authorUrl;628 }629 if (authorIconUrl !== undefined && authorIconUrl !== "") {630 // Validate authoriconurl is a valid url631 if (!/^(http|https):\/\/[^ "]+$/.test(authorIconUrl)) {632 throw new ExpectedFailure(633 InteractionOrRequestFinalStatus.EMBED_VALUE_EDITING_MALFORMED,634 "Author Icon URL is not a valid URL"635 );636 }637 currentStatus.embed.author.icon_url = authorIconUrl;638 }639 }640 await saveMessageToCache({641 key: messageGenerationKey,642 instance,643 data: currentStatus,644 });645 }646 const returnData = createEmbedMessageGenerationEmbed(647 messageGenerationKey,648 currentStatus649 );650 return {651 type: InteractionResponseType.UpdateMessage,652 data: {653 embeds: [returnData.embed],654 components: returnData.components,655 flags: MessageFlags.Ephemeral,656 },657 };...

Full Screen

Full Screen

integration-test.ts

Source:integration-test.ts Github

copy

Full Screen

1import { assert } from 'chai';2import axios from 'axios';3import { BunyanLogger as Logger } from '@danielemeryau/logger';4import { ProcessManager } from '../index';5import MockService from './mock-service';6const HEALTH_PORT = 5000;7const logger = new Logger('process-manager/integration-test', 'debug');8async function tick(): Promise<void> {9 return new Promise((res) => setTimeout(() => res(), 10));10}11async function getHealthZ() {12 let response;13 try {14 response = await axios.get(`http://localhost:${HEALTH_PORT}/healthz`);15 } catch (err: any) {16 response = err.response;17 }18 return {19 status: response.status,20 value: response.data,21 };22}23async function getReadyZ() {24 let response;25 try {26 response = await axios.get(`http://localhost:${HEALTH_PORT}/readyz`);27 } catch (err: any) {28 response = err.response;29 }30 return {31 status: response.status,32 value: response.data,33 };34}35async function runIntegrationTests() {36 const pm = new ProcessManager(logger, {37 healthResponseTimeMs: 1000,38 healthPort: HEALTH_PORT,39 });40 const serviceOne = new MockService('serviceOne');41 const serviceTwo = new MockService('serviceTwo');42 // Initial statuses43 let currentStatus = pm.getStatus();44 assert.deepEqual(currentStatus, {45 state: 'stopped',46 services: {},47 });48 let currentHealth = await pm.getHealth();49 assert.deepEqual(currentHealth, {50 healthy: 'healthy',51 services: {},52 });53 // Statuses after registration54 pm.registerService(serviceOne);55 pm.registerService(serviceTwo);56 // await tick();57 currentStatus = pm.getStatus();58 console.log(currentStatus);59 assert.equal(currentStatus.state, 'stopped');60 assert.equal(currentStatus.services['serviceOne'].state, 'stopped');61 assert.equal(currentStatus.services['serviceTwo'].state, 'stopped');62 // Starting statuses63 pm.start();64 await tick();65 currentStatus = pm.getStatus();66 let currentReadyZResult = await getReadyZ();67 assert.equal(currentStatus.state, 'starting');68 assert.equal(currentStatus.services['serviceOne'].state, 'starting');69 assert.equal(currentStatus.services['serviceTwo'].state, 'starting');70 assert.equal(currentReadyZResult.status, 503);71 // Partially started statuses72 serviceOne.mockNext();73 // await tick();74 currentStatus = pm.getStatus();75 assert.equal(currentStatus.state, 'starting');76 assert.equal(currentStatus.services['serviceOne'].state, 'running');77 assert.equal(currentStatus.services['serviceTwo'].state, 'starting');78 // Fully started statuses79 serviceTwo.mockNext();80 // await tick();81 currentStatus = pm.getStatus();82 assert.equal(currentStatus.state, 'running');83 assert.equal(currentStatus.services['serviceOne'].state, 'running');84 assert.equal(currentStatus.services['serviceTwo'].state, 'running');85 // Healthy statuses86 currentHealth = await pm.getHealth();87 let currentHealthZResult = await getHealthZ();88 assert.equal(currentHealth.healthy, 'healthy');89 assert.equal(currentHealth.services['serviceOne'].healthy, 'healthy');90 assert.equal(currentHealth.services['serviceTwo'].healthy, 'healthy');91 assert.equal(currentHealthZResult.status, 200);92 assert.deepEqual(currentHealthZResult.value, currentHealth);93 // Unhealthy statuses94 serviceOne.mockHealth('unhealthy');95 currentHealth = await pm.getHealth();96 currentHealthZResult = await getHealthZ();97 assert.equal(currentHealth.healthy, 'unhealthy');98 assert.equal(currentHealth.services['serviceOne'].healthy, 'unhealthy');99 assert.equal(currentHealth.services['serviceTwo'].healthy, 'healthy');100 assert.equal(currentHealthZResult.status, 503);101 assert.deepEqual(currentHealthZResult.value, currentHealth);102 // Stopping statuses103 pm.stop();104 await tick();105 currentStatus = pm.getStatus();106 assert.equal(currentStatus.state, 'stopping');107 assert.equal(currentStatus.services['serviceOne'].state, 'stopping');108 assert.equal(currentStatus.services['serviceTwo'].state, 'stopping');109 // Partially stopped statuses110 serviceTwo.mockNext();111 // await tick();112 currentStatus = pm.getStatus();113 assert.equal(currentStatus.state, 'stopping');114 assert.equal(currentStatus.services['serviceOne'].state, 'stopping');115 assert.equal(currentStatus.services['serviceTwo'].state, 'stopped');116 // Fully stopped status117 serviceOne.mockNext();118 // await tick();119 currentStatus = pm.getStatus();120 assert.equal(currentStatus.state, 'stopped');121 assert.equal(currentStatus.services['serviceOne'].state, 'stopped');122 assert.equal(currentStatus.services['serviceTwo'].state, 'stopped');123 // Partial error status124 pm.start();125 await tick();126 127 const startError = 'Failed to start service 2';128 serviceOne.mockNext();129 serviceTwo.mockNext(startError);130 currentStatus = pm.getStatus();131 assert.equal(currentStatus.state, 'errored');132 assert.equal(currentStatus.services['serviceOne'].state, 'running');133 assert.equal(currentStatus.services['serviceTwo'].state, 'errored');134 assert.deepEqual(currentStatus.services['serviceTwo'].message, startError);135}136runIntegrationTests()137 .then(() => {138 logger.info('Integration test completed successfully');139 process.exit(0);140 })141 .catch((err) => {142 logger.error('Unexpected error running integration tests', err);143 process.exit(1);...

Full Screen

Full Screen

reducer.ts

Source:reducer.ts Github

copy

Full Screen

1/**2 * Internal dependencies3 */4import {5 ACTION,6 STATUS,7 DEFAULT_PAYMENT_DATA_CONTEXT_STATE,8} from './constants';9import type { PaymentMethodDataContextState } from './types';10import type { ActionType } from './actions';11const hasSavedPaymentToken = (12 paymentMethodData: Record< string, unknown >13): boolean => {14 return !! (15 typeof paymentMethodData === 'object' && paymentMethodData.isSavedToken16 );17};18/**19 * Reducer for payment data state20 */21const reducer = (22 state = DEFAULT_PAYMENT_DATA_CONTEXT_STATE,23 {24 type,25 paymentMethodData = {},26 shouldSavePaymentMethod = false,27 errorMessage = '',28 paymentMethods = {},29 }: ActionType30): PaymentMethodDataContextState => {31 switch ( type ) {32 case STATUS.STARTED:33 return state.currentStatus !== STATUS.STARTED34 ? {35 ...state,36 currentStatus: STATUS.STARTED,37 }38 : state;39 case STATUS.ERROR:40 return state.currentStatus !== STATUS.ERROR41 ? {42 ...state,43 currentStatus: STATUS.ERROR,44 errorMessage: errorMessage || state.errorMessage,45 }46 : state;47 case STATUS.FAILED:48 return state.currentStatus !== STATUS.FAILED49 ? {50 ...state,51 currentStatus: STATUS.FAILED,52 paymentMethodData:53 paymentMethodData || state.paymentMethodData,54 errorMessage: errorMessage || state.errorMessage,55 }56 : state;57 case STATUS.SUCCESS:58 return state.currentStatus !== STATUS.SUCCESS59 ? {60 ...state,61 currentStatus: STATUS.SUCCESS,62 paymentMethodData:63 paymentMethodData || state.paymentMethodData,64 hasSavedToken: hasSavedPaymentToken(65 paymentMethodData66 ),67 }68 : state;69 case STATUS.PROCESSING:70 return state.currentStatus !== STATUS.PROCESSING71 ? {72 ...state,73 currentStatus: STATUS.PROCESSING,74 errorMessage: '',75 }76 : state;77 case STATUS.COMPLETE:78 return state.currentStatus !== STATUS.COMPLETE79 ? {80 ...state,81 currentStatus: STATUS.COMPLETE,82 }83 : state;84 case STATUS.PRISTINE:85 return {86 ...DEFAULT_PAYMENT_DATA_CONTEXT_STATE,87 currentStatus: STATUS.PRISTINE,88 // keep payment method registration state89 paymentMethods: {90 ...state.paymentMethods,91 },92 expressPaymentMethods: {93 ...state.expressPaymentMethods,94 },95 shouldSavePaymentMethod: state.shouldSavePaymentMethod,96 };97 case ACTION.SET_REGISTERED_PAYMENT_METHODS:98 return {99 ...state,100 paymentMethods,101 };102 case ACTION.SET_REGISTERED_EXPRESS_PAYMENT_METHODS:103 return {104 ...state,105 expressPaymentMethods: paymentMethods,106 };107 case ACTION.SET_SHOULD_SAVE_PAYMENT_METHOD:108 return {109 ...state,110 shouldSavePaymentMethod,111 };112 }113};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { LightningElement, track } from 'lwc';2import { ShowToastEvent } from 'lightning/platformShowToastEvent';3export default class Test extends LightningElement {4 @track isModalOpen = false;5 @track isModalOpen1 = false;6 @track isModalOpen2 = false;7 @track isModalOpen3 = false;8 @track isModalOpen4 = false;9 @track isModalOpen5 = false;10 @track isModalOpen6 = false;11 @track isModalOpen7 = false;12 @track isModalOpen8 = false;13 @track isModalOpen9 = false;14 @track isModalOpen10 = false;15 @track isModalOpen11 = false;16 @track isModalOpen12 = false;17 @track isModalOpen13 = false;18 @track isModalOpen14 = false;19 @track isModalOpen15 = false;20 @track isModalOpen16 = false;21 @track isModalOpen17 = false;22 @track isModalOpen18 = false;23 @track isModalOpen19 = false;24 @track isModalOpen20 = false;25 @track isModalOpen21 = false;26 @track isModalOpen22 = false;27 @track isModalOpen23 = false;28 @track isModalOpen24 = false;29 @track isModalOpen25 = false;30 @track isModalOpen26 = false;31 @track isModalOpen27 = false;32 @track isModalOpen28 = false;33 @track isModalOpen29 = false;34 @track isModalOpen30 = false;35 @track isModalOpen31 = false;36 @track isModalOpen32 = false;37 @track isModalOpen33 = false;38 @track isModalOpen34 = false;39 @track isModalOpen35 = false;40 @track isModalOpen36 = false;41 @track isModalOpen37 = false;42 @track isModalOpen38 = false;43 @track isModalOpen39 = false;44 @track isModalOpen40 = false;45 @track isModalOpen41 = false;46 @track isModalOpen42 = false;47 @track isModalOpen43 = false;48 @track isModalOpen44 = false;49 @track isModalOpen45 = false;

Full Screen

Using AI Code Generation

copy

Full Screen

1import { useSelector } from 'react-redux';2const currentStatus = useSelector(state => state.currentStatus);3console.log(currentStatus);4import { combineReducers } from 'redux';5import currentStatus from './currentStatus';6export default combineReducers({7})8const currentStatus = (state = 'loading', action) => {9 switch (action.type) {10 return action.payload;11 return state;12 }13}14export default currentStatus;15import React from 'react';16import { connect } from 'react-redux';17import { setStatus } from './redux/action';18import './App.css';19function App(props) {20 const { status, setStatus } = props;21 const handleStatus = () => {22 setStatus('loading');23 setTimeout(() => {24 setStatus('success');25 }, 3000);26 }27 return (28 <h1>{status}</h1>29 <button onClick={handleStatus}>Click</button>30 );31}32const mapStateToProps = state => {33 return {34 }35}36const mapDispatchToProps = dispatch => {37 return {38 setStatus: (status) => dispatch(setStatus(status))39 }40}41export default connect(mapStateToProps, mapDispatchToProps)(App);42export const setStatus = (status) => {43 return {44 }45}46export default setStatus;47import React from 'react';48import ReactDOM from 'react-dom';49import App from './App';50import { Provider } from 'react-redux';51import { createStore } from 'redux';52import rootReducer from './redux/reducer';53const store = createStore(rootReducer);54ReactDOM.render(55 <Provider store={store}>56 </Provider>, document.getElementById('root')57);58.App {59 text-align: center;60}61.App-logo {62 height: 40vmin;63 pointer-events: none;64}65.App-header {66 background-color: #282c34;

Full Screen

Using AI Code Generation

copy

Full Screen

1var root = require('./root.js');2var status = root.currentStatus();3console.log(status);4var root = require('./root.js');5var status = root.currentStatus();6console.log(status);7var root = require('./root.js');8var status = root.currentStatus();9console.log(status);10var root = require('./root.js');11var status = root.currentStatus();12console.log(status);13var root = require('./root.js');14var status = root.currentStatus();15console.log(status);16var root = require('./root.js');17var status = root.currentStatus();18console.log(status);19var root = require('./root.js');20var status = root.currentStatus();21console.log(status);22var root = require('./root.js');23var status = root.currentStatus();24console.log(status);25var root = require('./root.js');26var status = root.currentStatus();27console.log(status);28var root = require('./root.js');29var status = root.currentStatus();30console.log(status);31var root = require('./root.js');32var status = root.currentStatus();33console.log(status);34var root = require('./root.js');35var status = root.currentStatus();36console.log(status);

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