github.com/Redstoneguy129/cli@v0.0.0-20230211220159-15dca4e91917/internal/functions/delete/delete.go (about)

     1  package delete
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  	"net/http"
     8  
     9  	"github.com/spf13/afero"
    10  	"github.com/Redstoneguy129/cli/internal/utils"
    11  )
    12  
    13  func Run(ctx context.Context, slug string, projectRefArg string, fsys afero.Fs) error {
    14  	// 1. Sanity checks.
    15  	projectRef := projectRefArg
    16  	{
    17  		if len(projectRefArg) == 0 {
    18  			ref, err := utils.LoadProjectRef(fsys)
    19  			if err != nil {
    20  				return err
    21  			}
    22  			projectRef = ref
    23  		} else if !utils.ProjectRefPattern.MatchString(projectRefArg) {
    24  			return errors.New("Invalid project ref format. Must be like `abcdefghijklmnopqrst`.")
    25  		}
    26  		if err := utils.ValidateFunctionSlug(slug); err != nil {
    27  			return err
    28  		}
    29  	}
    30  
    31  	// 2. Delete Function.
    32  	{
    33  		resp, err := utils.GetSupabase().GetFunctionWithResponse(ctx, projectRef, slug)
    34  		if err != nil {
    35  			return err
    36  		}
    37  
    38  		switch resp.StatusCode() {
    39  		case http.StatusNotFound: // Function doesn't exist
    40  			return errors.New("Function " + utils.Aqua(slug) + " does not exist on the Supabase project.")
    41  		case http.StatusOK: // Function exists
    42  			resp, err := utils.GetSupabase().DeleteFunctionWithResponse(ctx, projectRef, slug)
    43  			if err != nil {
    44  				return err
    45  			}
    46  			if resp.StatusCode() != http.StatusOK {
    47  				return errors.New("Failed to delete Function " + utils.Aqua(slug) + " on the Supabase project: " + string(resp.Body))
    48  			}
    49  		default:
    50  			return errors.New("Unexpected error deleting Function: " + string(resp.Body))
    51  		}
    52  	}
    53  
    54  	fmt.Println("Deleted Function " + utils.Aqua(slug) + " from project " + utils.Aqua(projectRef) + ".")
    55  	return nil
    56  }