Secreto31126 / whatsapp-api-js

A TypeScript server agnostic Whatsapp's Official API framework
MIT License
142 stars 33 forks source link

Pass BodyParameters[] to BodyComponent #317

Closed angelopedroso closed 7 months ago

angelopedroso commented 7 months ago

Is there a way to pass an array of BodyParameter to the BodyComponent?

My current code:

const bodies = (data.params.body || []).map(
        (item) => new BodyParameter(item),
 ) as any

if (bodies.length > 0) {
        editableTemplate.components.push(new BodyComponent(bodies))
}
angelopedroso commented 7 months ago

I did this "trick":

editableTemplate.components.push(
    new (Function.prototype.bind.apply(BodyComponent, [
      null,
      ...bodies,
    ]))(),
 )
Secreto31126 commented 7 months ago

Why not just:

const params = [
    new BodyParameter("User"),
    new BodyParameter(new DateTime("06-03-2024")
];

const component = new BodyComponent(
    ...params
);

A template should take a single header and body component, else the values will be overwritten.

Think of the components as the sections of the template: the Header, Body and each button is treated as a section by the API, and each variable of the section is a parameter.

angelopedroso commented 7 months ago

Why not just:

const params = [
    new BodyParameter("User"),
    new BodyParameter(new DateTime("06-03-2024")
];

const component = new BodyComponent(
    ...params
);

A template should take a single header and body component, else the values will be overwritten.

Think of the components as the sections of the template: the Header, Body and each button is treated as a section by the API, and each variable of the section is a parameter.

I get a typescript error saying: "A spread argument must either have a tuple type or be passed to a rest parameter."

Secreto31126 commented 7 months ago

Huh, that seems to be an unfortunate edge case where the AtLeastOne type doesn't work as expected.

You can either:

const params = [
    new BodyParameter("User"),
    new BodyParameter(new DateTime("06-03-2024"))
];

const component = new BodyComponent(
    params[0],
    ...params.slice(1)
);

Or use // @ ts-ignore - The argument is a rest parameter

I won't be fixing this error as it only affects this edge case, which is not a design pattern I would like to encourage since Templates should have a fixed amount of variables.