Skip to content

Commit

Permalink
fix: don't create new instances of builders classes (#7343)
Browse files Browse the repository at this point in the history
  • Loading branch information
ImRodry committed Jan 26, 2022
1 parent b640272 commit d6b56d0
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
4 changes: 3 additions & 1 deletion packages/builders/src/components/ActionRow.ts
Expand Up @@ -3,14 +3,16 @@ import type { ButtonComponent, SelectMenuComponent } from '..';
import type { Component } from './Component';
import { createComponent } from './Components';

export type MessageComponent = ActionRowComponent | ActionRow;

export type ActionRowComponent = ButtonComponent | SelectMenuComponent;

// TODO: Add valid form component types

/**
* Represents an action row component
*/
export class ActionRow<T extends ActionRowComponent> implements Component {
export class ActionRow<T extends ActionRowComponent = ActionRowComponent> implements Component {
public readonly components: T[] = [];
public readonly type = ComponentType.ActionRow;

Expand Down
13 changes: 7 additions & 6 deletions packages/builders/src/components/Components.ts
@@ -1,9 +1,9 @@
import { APIMessageComponent, ComponentType } from 'discord-api-types/v9';
import { ActionRow, ButtonComponent, Component, SelectMenuComponent } from '../index';
import type { ActionRowComponent } from './ActionRow';
import type { MessageComponent } from './ActionRow';

export interface MappedComponentTypes {
[ComponentType.ActionRow]: ActionRow<ActionRowComponent>;
[ComponentType.ActionRow]: ActionRow;
[ComponentType.Button]: ButtonComponent;
[ComponentType.SelectMenu]: SelectMenuComponent;
}
Expand All @@ -15,14 +15,15 @@ export interface MappedComponentTypes {
export function createComponent<T extends keyof MappedComponentTypes>(
data: APIMessageComponent & { type: T },
): MappedComponentTypes[T];
export function createComponent(data: APIMessageComponent): Component {
export function createComponent<C extends MessageComponent>(data: C): C;
export function createComponent(data: APIMessageComponent | MessageComponent): Component {
switch (data.type) {
case ComponentType.ActionRow:
return new ActionRow(data);
return data instanceof ActionRow ? data : new ActionRow(data);
case ComponentType.Button:
return new ButtonComponent(data);
return data instanceof ButtonComponent ? data : new ButtonComponent(data);
case ComponentType.SelectMenu:
return new SelectMenuComponent(data);
return data instanceof SelectMenuComponent ? data : new SelectMenuComponent(data);
default:
// @ts-expect-error
throw new Error(`Cannot serialize component type: ${data.type as number}`);
Expand Down

0 comments on commit d6b56d0

Please sign in to comment.