Skip to content

Improvement ideas for PostSSE element sugar #8

@michaeldebetaz

Description

@michaeldebetaz

Hi guys and thanks for this great SDK, I'm loving using Datastart with Go!

I found out there is a Get/Post/etcSSE helper function to build the @post('url') string, which I find useful to avoid typos. In practice, I was limited by the fact that it only allows to build the url inside the single quotes.

That means I can't use it if I want to add options @post('url', { contentType: 'form' }).

Following the implementation of PatchElements, I was thinking of an implementation like this, that would have type safety and autocompletion:

package main

import (
	"fmt"
	"strings"
)

func main() {
	s := PostSSE("/endpoint", WithContentType("form"), WithOpenWhenHidden(true))
	fmt.Println(s)
}

type PostSSEOptions struct {
	ContentType    string
	OpenWhenHidden bool
}

type PostSSEOption func(o *PostSSEOptions)

func WithContentType(contentType string) PostSSEOption {
	return func(o *PostSSEOptions) {
		o.ContentType = contentType
	}
}

func WithOpenWhenHidden(openWhenHidden bool) PostSSEOption {
	return func(o *PostSSEOptions) {
		o.OpenWhenHidden = openWhenHidden
	}
}

func PostSSE(url string, opts ...PostSSEOption) string {
	if len(opts) == 0 {
		return fmt.Sprintf("@post('%s')", url)
	}

	options := &PostSSEOptions{
		ContentType:    "",
		OpenWhenHidden: false,
	}
	for _, opt := range opts {
		opt(options)
	}

	result := fmt.Sprintf("@post('%s',{", url)

	items := []string{}

	if options.ContentType != "" {
		items = append(items, fmt.Sprintf("contentType:'%s'", options.ContentType))
	}

	if options.OpenWhenHidden {
		items = append(items, "openWhenHidden:true")
	}

	optsStr := strings.Join(items, ",")

	result += optsStr + "})"

	return result
}

Here is a playground: https://goplay.tools/snippet/MMYkwIxRIyV

Unfortunately, that would be a breaking change. Also, maybe you prefer let the user define those functions so it wouldn't be a burden to maintain for futur iterations of Datastar.

I would be happy to contribute of course if you confirm a prefered way to do this! I have no idea how to build strings efficiently.

What do you think ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions