uuid#v4 TypeScript Examples

The following examples show how to use uuid#v4. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: canvas-react-utils.ts    From utopia with MIT License 7 votes vote down vote up
mangleClassType = Utils.memoize(
  (type: any) => {
    const originalRender = type.prototype.render
    // mutation
    type.prototype.render = function monkeyRender() {
      const MeasureRenderTimes =
        isFeatureEnabled('Debug mode – Performance Marks') && PERFORMANCE_MARKS_ALLOWED
      const uuid = MeasureRenderTimes ? v4() : ''
      if (MeasureRenderTimes) {
        performance.mark(`render_start_${uuid}`)
      }
      let originalTypeResponse = originalRender.bind(this)()
      const res = attachDataUidToRoot(
        originalTypeResponse,
        (this.props as any)?.[UTOPIA_UID_KEY],
        (this.props as any)?.[UTOPIA_PATH_KEY],
      )
      if (MeasureRenderTimes) {
        performance.mark(`render_end_${uuid}`)
        performance.measure(
          `Render ComponentClass ${getDisplayName(type)}`,
          `render_start_${uuid}`,
          `render_end_${uuid}`,
        )
      }
      return res
    }
    ;(type as any).theOriginalType = type
    ;(type as any).displayName = `UtopiaSpiedClass(${getDisplayName(type)})`
    return type
  },
  {
    maxSize: 10000,
  },
)
Example #2
Source File: CollectionBlock.test.ts    From Nishan with MIT License 6 votes vote down vote up
it(`createViews`, async () => {
  const view_id = v4();
  const {collection_block, block_1, executeOperationsMock} = construct();
	const createViews_params: TViewCreateInput[] = [
		{
      id: view_id,
			type: 'table',
			name: 'Table',
			schema_units: [
				tsu
			]
		}
	];
	
  const view_map = await collection_block.createViews(createViews_params);

	expect(executeOperationsMock.mock.calls[0][0].slice(1)).toStrictEqual(
		[
      o.b.s('block_1', ['view_ids'], [ 'collection_view_1', view_id ]),
      o.b.u('block_1', [], last_edited_props)
    ]
  );
  expect(block_1.view_ids).toStrictEqual(['collection_view_1', view_id]);
  expect(view_map.table.get("Table")).toStrictEqual(expect.objectContaining({id: view_id}))
});
Example #3
Source File: userStorage.ts    From space-sdk with MIT License 6 votes vote down vote up
/**
   * Creates an empty folder at the requested path and bucket.
   *
   * @remarks
   * - It throws if an error occurred while creating the folder
   */
  public async createFolder(request: CreateFolderRequest): Promise<void> {
    const client = this.getUserBucketsClient();
    const metadataStore = await this.getMetadataStore();

    const bucket = await this.getOrCreateBucket(client, request.bucket);
    const file = {
      path: `${sanitizePath(request.path.trimStart())}/.keep`,
      content: Buffer.from(''),
    };

    await metadataStore.upsertFileMetadata({
      uuid: v4(),
      bucketKey: bucket.root?.key,
      bucketSlug: bucket.slug,
      dbId: bucket.dbId,
      encryptionKey: generateFileEncryptionKey(),
      path: file.path,
    });
    await client.pushPath(bucket.root?.key || '', '.keep', file);
  }
Example #4
Source File: environment_router.ts    From Daemon with GNU Affero General Public License v3.0 6 votes vote down vote up
// 创建镜像
routerApp.on("environment/new_image", async (ctx, data) => {
  if (os.platform() === "win32") return protocol.responseError(ctx, "[Unsupported] Windows 系统暂不支持此功能");
  try {
    const dockerFileText = data.dockerFile;
    const name = data.name;
    const tag = data.tag;
    // 初始化镜像文件目录和 Dockerfile
    const uuid = v4();
    const dockerFileDir = path.normalize(path.join(process.cwd(), "tmp", uuid));
    if (!fs.existsSync(dockerFileDir)) fs.mkdirsSync(dockerFileDir);

    // 写入 DockerFile
    const dockerFilepath = path.normalize(path.join(dockerFileDir, "Dockerfile"));
    await fs.writeFile(dockerFilepath, dockerFileText, { encoding: "utf-8" });

    logger.info(`守护进程正在创建镜像 ${name}:${tag} DockerFile 如下:\n${dockerFileText}\n`);

    // 预先响应
    protocol.response(ctx, true);

    // 开始创建
    const dockerImageName = `${name}:${tag}`;
    try {
      await new DockerManager().startBuildImage(dockerFileDir, dockerImageName);
      logger.info(`创建镜像 ${name}:${tag} 完毕`);
    } catch (error) {
      logger.info(`创建镜像 ${name}:${tag} 错误:${error}`);
    }
  } catch (error) {
    protocol.responseError(ctx, error);
  }
});
Example #5
Source File: files.controller.ts    From NestJs-youtube with MIT License 6 votes vote down vote up
@Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: (req: Express.Request, file: Express.Multer.File, cb) =>
          cb(null, 'public/uploads'),
        filename: (req: Express.Request, file: Express.Multer.File, cb) => {
          // mimetype: 'image/jpeg',
          const [, ext] = file.mimetype.split('/');
          FilesController.genericSercive.pcoket.filename = `${v4()}.${ext}`;
          cb(null, FilesController.genericSercive.pcoket.filename);
        },
      }),
      limits: {
        fileSize: 1e7, // the max file size in bytes, here it's 100MB,
        files: 1,
      },
    }),
  )
  uploadFile(@UploadedFile() file: Express.Multer.File): Promise<FileEntity> {
    const [, ext] = file.mimetype.split('/');
    this.saveImages(ext, file);
    return this.service.dbSave(
      file,
      FilesController.genericSercive.pcoket.filename,
    );
  }
Example #6
Source File: index.ts    From metaflow-ui with Apache License 2.0 6 votes vote down vote up
function useOnKeyPress(key: string, callback: () => void): void {
  const [hookid] = useState(v4());

  useEffect(() => {
    if (!callbackStore[key]) {
      callbackStore[key] = {};
    }
    callbackStore[key][hookid] = callback;

    return () => {
      delete callbackStore[key][hookid];
    };
  }, []); // eslint-disable-line
}
Example #7
Source File: database.ts    From End-to-End-Web-Testing-with-Cypress with MIT License 6 votes vote down vote up
createUser = (userDetails: Partial<User>): User => {
  const password = bcrypt.hashSync(userDetails.password!, 10);
  const user: User = {
    id: shortid(),
    uuid: v4(),
    firstName: userDetails.firstName!,
    lastName: userDetails.lastName!,
    username: userDetails.username!,
    password,
    email: userDetails.email!,
    phoneNumber: userDetails.phoneNumber!,
    balance: userDetails.balance! || 0,
    avatar: userDetails.avatar!,
    defaultPrivacyLevel: userDetails.defaultPrivacyLevel!,
    createdAt: new Date(),
    modifiedAt: new Date(),
  };

  saveUser(user);
  return user;
}
Example #8
Source File: db.ts    From Full-Stack-React-TypeScript-and-Node with MIT License 6 votes vote down vote up
todos = [
  {
    id: v4(),
    title: "First todo",
    description: "First todo description",
  },
  {
    id: v4(),
    title: "Second todo",
    description: "Second todo description",
  },
  {
    id: v4(),
    title: "Third todo",
  },
]
Example #9
Source File: broker.ts    From posthog-foss with MIT License 6 votes vote down vote up
/**
     * @method RedisBroker#publish
     *
     * @returns {Promise}
     */
    public publish(
        body: Record<string, any> | [Array<any>, Record<string, any>, Record<string, any>],
        exchange: string,
        routingKey: string,
        headers: Record<string, any>,
        properties: Record<string, any>
    ): Promise<number> {
        const messageBody = JSON.stringify(body)
        const contentType = 'application/json'
        const contentEncoding = 'utf-8'
        const message = {
            body: Buffer.from(messageBody).toString('base64'),
            'content-type': contentType,
            'content-encoding': contentEncoding,
            headers,
            properties: {
                body_encoding: 'base64',
                delivery_info: {
                    exchange: exchange,
                    routing_key: routingKey,
                },
                delivery_mode: 2,
                delivery_tag: v4(),
                ...properties,
            },
        }

        return this.db.redisLPush(routingKey, message)
    }
Example #10
Source File: heroes.sagas.ts    From nestjs-geteventstore with MIT License 6 votes vote down vote up
@Saga()
  dragonKilled = (events$: Observable<any>): Observable<ICommand> => {
    return events$.pipe(
      //@ts-ignore
      filter((ev) => ev instanceof HeroKilledDragonEvent),
      //@ts-ignore
      delay(400),
      //@ts-ignore
      map((event: HeroKilledDragonEvent) => {
        this.context.setCachedValue(
          CONTEXT_CORRELATION_ID,
          event?.metadata?.correlation_id || v4(),
        );
        console.log(
          clc.redBright('Inside [HeroesGameSagas] Saga after a little sleep'),
        );
        console.log(event);
        return new DropAncientItemCommand(event.data.heroId, itemId);
      }),
    );
  };
Example #11
Source File: index.ts    From your_spotify with GNU General Public License v3.0 6 votes vote down vote up
router.post('/generate-public-token', logged, async (req, res) => {
  const { user } = req as LoggedRequest;

  try {
    const token = v4();
    await setUserPublicToken(user._id.toString(), token);
    return res.status(200).send(token);
  } catch (e) {
    logger.error(e);
    return res.status(500).end();
  }
});
Example #12
Source File: UiConsoleComponent.tsx    From BlinkWebUI with GNU General Public License v3.0 6 votes vote down vote up
constructor(props: {}) {
        super(props);
        this.state = {
            alerts: []
        };

        Object
            .keys(UiConsoleComponent.eventsToTypeMap)
            .forEach((key: string) => {
                const pubSubEventKey = key as unknown as PubSubEvent;
                SimplePubSub.subscribe(pubSubEventKey, (ev) => {
                    const alertType = UiConsoleComponent.eventsToTypeMap[pubSubEventKey] as UIConsoleAlertType;
                    const newAlert = {
                        id: v4(),
                        message: ev.message,
                        type: alertType
                    };

                    if ([UIConsoleAlertType.INFO, UIConsoleAlertType.SUCCESS].includes(alertType)) {
                        setTimeout(() => {
                            this.onAlertDismissed(newAlert);
                        }, 5000);
                    }

                    this.setState((prevState) => {
                        const alerts = [...prevState.alerts];
                        alerts.unshift(newAlert);
                        return {
                            alerts: alerts.slice(0, 5)
                        };
                    });
                });
            });
    }
Example #13
Source File: generateCredentials.ts    From affinidi-core-sdk with Apache License 2.0 6 votes vote down vote up
generateCredential = (types: string[] = []) => {
  const credential = {
    id: v4(),
    type: types,
    issuer: v4(),
  } as SignedCredential

  return credential
}
Example #14
Source File: Room.helpers.tsx    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
sendMessageOptimisticResponse = (
  roomId: string,
  content: string,
  user: Me
): SendMessageMutation => {
  return {
    __typename: "Mutation",
    sendMessage: {
      __typename: "Message",
      id: v4(),
      roomId,
      content: content,
      mentions: [],
      createdAt: Date.now(),
      author: {
        color: user.color,
        id: user.id,
        name: user.name,
        username: user.username,
        avatarUrl: user.avatarUrl,
        __typename: "Member",
      },
    },
  };
}
Example #15
Source File: user.ts    From lireddit with MIT License 6 votes vote down vote up
@Mutation(() => Boolean)
  async forgotPassword(
    @Arg("email") email: string,
    @Ctx() { redis }: MyContext
  ) {
    const user = await User.findOne({ where: { email } });
    if (!user) {
      // the email is not in the db
      return true;
    }

    const token = v4();

    await redis.set(
      FORGET_PASSWORD_PREFIX + token,
      user.id,
      "ex",
      1000 * 60 * 60 * 24 * 3
    ); // 3 days

    await sendEmail(
      email,
      `<a href="http://localhost:3000/change-password/${token}">reset password</a>`
    );

    return true;
  }
Example #16
Source File: application-lifecycle.ts    From malagu with MIT License 6 votes vote down vote up
initialize(): void {
        if (this.scheduleDisabled) {
            return;
        }
        for (const scheduler of this.shedulers) {
            const targetConstructor = getTargetClass(scheduler);
            const schedulerMetadata = <SchedulerMetadata>Reflect.getOwnMetadata(METADATA_KEY.scheduler, targetConstructor);
            const cronMetadatas = <CronMetadata[]>getOwnMetadata(METADATA_KEY.cron, targetConstructor);
            for (const cronMetadata of cronMetadatas) {
                const name = cronMetadata.name || v4();
                const method = cronMetadata.method;
                this.schedulerRegistry.add(name, {
                    ...schedulerMetadata,
                    ...cronMetadata,
                    onTick: async () => {
                        try {
                            await scheduler[method]();
                        } catch (error) {
                            this.logger.error(error);
                        }
                    }
                }).start();
            }

        }
    }
Example #17
Source File: canvas-react-utils.ts    From utopia with MIT License 6 votes vote down vote up
mangleFunctionType = Utils.memoize(
  (type: unknown): React.FunctionComponent<React.PropsWithChildren<unknown>> => {
    const mangledFunctionName = `UtopiaSpiedFunctionComponent(${getDisplayName(type)})`

    const mangledFunction = {
      [mangledFunctionName]: (p: any, context?: any) => {
        const MeasureRenderTimes =
          isFeatureEnabled('Debug mode – Performance Marks') && PERFORMANCE_MARKS_ALLOWED
        const uuid = MeasureRenderTimes ? v4() : ''
        if (MeasureRenderTimes) {
          performance.mark(`render_start_${uuid}`)
        }
        let originalTypeResponse = (
          type as React.FunctionComponent<React.PropsWithChildren<unknown>>
        )(p, context)
        const res = attachDataUidToRoot(
          originalTypeResponse,
          (p as any)?.[UTOPIA_UID_KEY],
          (p as any)?.[UTOPIA_PATH_KEY],
        )
        if (MeasureRenderTimes) {
          performance.mark(`render_end_${uuid}`)
          performance.measure(
            `Render Component ${getDisplayName(type)}`,
            `render_start_${uuid}`,
            `render_end_${uuid}`,
          )
        }
        return res
      },
    }[mangledFunctionName]
    ;(mangledFunction as any).theOriginalType = type
    ;(mangledFunction as any).contextTypes = (type as any).contextTypes
    ;(mangledFunction as any).childContextTypes = (type as any).childContextTypes
    ;(mangledFunction as any).displayName = `UtopiaSpiedFunctionComponent(${getDisplayName(type)})`
    return mangledFunction
  },
  {
    maxSize: 10000,
  },
)
Example #18
Source File: ProxyShim.ts    From ace with GNU Affero General Public License v3.0 6 votes vote down vote up
Coherent = {
        trigger: (name: string, ...data: string[]): any => {
            this.simCallListener.onCoherentTrigger?.(name, data, this.instrumentUniqueID);

            return this.shim.Coherent.trigger(name, ...data);
        },

        on: (name: string, callback: (data: string) => void): { clear: () => void } => {
            const data: CoherentEventData = { name, callback, uuid: v4(), timestamp: new Date(), instrumentUniqueId: this.instrumentUniqueID };

            const clear = () => {
                this.simCallListener.onCoherentClearListener?.(data, this.instrumentUniqueID);
                value.clear();
            };

            this.simCallListener.onCoherentNewListener?.(data, clear, this.instrumentUniqueID);
            const value = this.shim.Coherent.on(name, callback);
            return {
                ...value,
                clear,
            };
        },

        call: <T>(name: string, ...args: any[]): Promise<T> => {
            this.simCallListener.onCoherentCall?.(name, args, this.instrumentUniqueID);

            return this.shim.Coherent.call(name, ...args);
        },
    };
Example #19
Source File: habit-actions.ts    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
addHabit = (
  title: string,
  description = '',
  period: Period,
  id?: string
): AppThunk => async (dispatch) => {
  const days = new Map()

  const habit: Habit = {
    id: id || v4(),
    userId: null,
    title: title.trim(),
    description: convertLineBreaks(description.trim()),
    days,
    date: startOfDay(new Date()).toISOString(),
    period
  }

  await dispatch(updateEditedHabit(habit))
  await dispatch(stashHabitToSync(habit, MutationType.CREATE))
}
Example #20
Source File: testDataBuilder.ts    From cognito-local with MIT License 6 votes vote down vote up
user = (partial?: Partial<User>): User => ({
  Attributes: partial?.Attributes ?? [
    { Name: "sub", Value: v4() },
    { Name: "email", Value: `${id("example")}@example.com` },
  ],
  AttributeVerificationCode: partial?.AttributeVerificationCode ?? undefined,
  ConfirmationCode: partial?.ConfirmationCode ?? undefined,
  Enabled: partial?.Enabled ?? true,
  MFACode: partial?.MFACode ?? undefined,
  MFAOptions: partial?.MFAOptions ?? undefined,
  Password: partial?.Password ?? "Password123!",
  UserCreateDate: partial?.UserCreateDate ?? new Date(),
  UserLastModifiedDate: partial?.UserLastModifiedDate ?? new Date(),
  Username: partial?.Username ?? id("User"),
  UserStatus: partial?.UserStatus ?? "CONFIRMED",
  RefreshTokens: [],
})
Example #21
Source File: Media.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
constructor(payload: CreateMediaEntityPayload) {
    super();
  
    this.ownerId   = payload.ownerId;
    this.name      = payload.name;
    this.type      = payload.type;
    this.metadata  = payload.metadata;
    
    this.id        = payload.id || v4();
    this.createdAt = payload.createdAt || new Date();
    this.editedAt  = payload.editedAt || null;
    this.removedAt = payload.removedAt || null;
  }
Example #22
Source File: uuid-handler.spec.ts    From advanced-node with GNU General Public License v3.0 6 votes vote down vote up
describe('UUIDHandler', () => {
  let sut: UUIDHandler

  beforeAll(() => {
    mocked(v4).mockReturnValue('any_uuid')
  })

  beforeEach(() => {
    sut = new UUIDHandler()
  })

  it('should call uuid.v4', () => {
    sut.uuid({ key: 'any_key' })

    expect(v4).toHaveBeenCalledTimes(1)
  })

  it('should return correct uuid', () => {
    const uuid = sut.uuid({ key: 'any_key' })

    expect(uuid).toBe('any_key_any_uuid')
  })
})
Example #23
Source File: FakeTossBillingController.ts    From fake-toss-payments-server with MIT License 6 votes vote down vote up
/**
     * 간편 결제 카드 등록하기.
     *
     * `billing.authorizations.card.store` 는 고객이 자신의 신록 카드를 서버에 등록해두고,
     * 매번 결제가 필요할 때마다 카드 정보를 반복 입력하는 일 없이 간편하게 결제를
     * 진행하고자 할 때, 호출되는 API 함수이다.
     *
     * 참고로 `billing.authorizations.card.store` 는 클라이언트 어플리케이션이 토스
     * 페이먼츠가 제공하는 간편 결제 카드 등록 창을 사용하는 경우, 귀하의 백엔드 서버가 이를
     * 실 서비스에서 호출하는 일은 없을 것이다. 다만, 고객이 간편 결제 카드를 등록하는
     * 상황을 시뮬레이션하기 위하여, 테스트 자동화 프로그램 수준에서 사용될 수는 있다.
     *
     * @param input 간편 결제 카드 등록 정보
     * @returns 간편 결제 카드 정보
     *
     * @author Jeongho Nam - https://github.com/samchon
     */
    @helper.TypedRoute.Post("authorizations/card")
    public store(
        @nest.Request() request: express.Request,
        @nest.Body() input: ITossBilling.IStore,
    ): ITossBilling {
        FakeTossUserAuth.authorize(request);
        assertType<typeof input>(input);

        const billing: ITossBilling = {
            mId: "tosspyaments",
            method: "카드",
            billingKey: v4(),
            customerKey: input.customerKey,
            cardCompany: "신한",
            cardNumber: input.cardNumber,
            authenticatedAt: new Date().toString(),
        };
        FakeTossStorage.billings.set(billing.billingKey, [billing, input]);
        return billing;
    }
Example #24
Source File: actions.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
onEditorAdd = (identifier: VariableIdentifier): ThunkResult<void> => {
  return async (dispatch, getState) => {
    const uuid = v4();
    dispatch(storeNewVariable(toVariablePayload({ type: identifier.type, uuid })));
    const variableInState = getVariable(uuid, getState());
    await variableAdapters.get(variableInState.type).updateOptions(variableInState);
    dispatch(switchToListMode());
    dispatch(removeVariable(toVariablePayload({ type: identifier.type, uuid: EMPTY_UUID }, { reIndex: false })));
  };
}
Example #25
Source File: twilio.module.ts    From twilio-voice-notification-app with Apache License 2.0 6 votes vote down vote up
mockedTwilioService = {
  async createCall() {
    return Promise.resolve({
      callSid: v4(),
      status: 'initated',
    });
  },
  async getPhoneNumbers() {
    return Promise.resolve([
      {
        capabilities: {
          voice: true,
          sms: true,
        },
        phoneNumber: '+35625211106',
      },
      {
        capabilities: {
          voice: true,
          sms: true,
        },
        phoneNumber: '+35625211107',
      },
    ]);
  },
}
Example #26
Source File: students.ts    From studentApp with MIT License 6 votes vote down vote up
students: student[] = [
	{
		id: v4(),
		Name: "Mohan",
		RollNo: 1,
		Class: 5,
		Section: "D"
	},
	{
		id: v4(),
		Name: "Sohan",
		RollNo: 1,
		Class: 6,
		Section: "D"
	},
]
Example #27
Source File: ClientAuthorization.ts    From keycloak-lambda-authorizer with Apache License 2.0 6 votes vote down vote up
async createJWS(requestContent:RequestContent): Promise<JWSPayload> {
    const timeLocal = new Date().getTime();
    const timeSec = Math.floor(timeLocal / 1000);
    const keycloakJson = await this.options.keycloakJson(this.options, requestContent);
    return {
      jti: v4(),
      sub: keycloakJson.resource,
      iss: keycloakJson.resource,
      aud: `${getKeycloakUrl(keycloakJson)}/realms/${keycloakJson.realm}`,
      exp: timeSec + 30,
      iat: timeSec,
    };
  }
Example #28
Source File: RealtimeSubscribeChatClient.ts    From flect-chime-sdk-demo with Apache License 2.0 6 votes vote down vote up
sendChatData = (text: string) => {
        console.log("chatdata::", this._chimeClient.attendeeId);
        const mess: RealtimeData = {
            uuid: v4(),
            action: "sendmessage",
            app: RealtimeDataApp.CHAT,
            data: text,
            createdDate: new Date().getTime(),
            senderId: this._chimeClient.attendeeId ? this._chimeClient.attendeeId : "unknown..",
        };
        this._chimeClient.meetingSession?.audioVideo!.realtimeSendDataMessage(RealtimeDataApp.CHAT, JSON.stringify(mess));
        // this._cahtData.push(mess)
        this._chatData = [...this._chatData, mess];
        this._realtimeSubscribeChatClientListener?.chatDataUpdated(this._chatData);
    };
Example #29
Source File: stompx.ts    From chatkitty-js with MIT License 5 votes vote down vote up
private static generateSubscriptionId(): string {
    return 'subscription-id-' + v4();
  }