package main import ( "bytes" "encoding/json" "errors" "fmt" "io" "net/http" tea "github.com/charmbracelet/bubbletea" ) const apiVersion = 6 type addNote struct { Action string `json:"action"` Version int `json:"version"` Params addNoteParams `json:"params"` } type addNoteParams struct { Note note `json:"note"` } type note struct { DeckName string `json:"deckName"` ModelName string `json:"modelName"` // Fields will not be trivial to generalize Fields fields `json:"fields"` Options options `json:"options"` } type fields struct { Front string `json:"Front"` Back string `json:"Back"` } type options struct { AllowDuplicate bool `json:"allowDuplicate"` DuplicateScope string `json:"duplicateScope"` } func addCard(c *http.Client, deckName, modelName, front, back string) tea.Cmd { return func() tea.Msg { if back == "" { return errMsg(errors.New("definition is blank")) } if front == "" { return errMsg(errors.New("word is blank")) } noteRequest := addNote{ Action: "addNote", Version: apiVersion, Params: addNoteParams{ Note: note{ DeckName: deckName, ModelName: modelName, Fields: fields{ Front: front, Back: back, }, Options: options{ AllowDuplicate: false, DuplicateScope: "deck", }, }, }, } jsonBytes, err := json.Marshal(noteRequest) if err != nil { return errMsg(fmt.Errorf("marshaling JSON: %s", err)) } req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonBytes)) req.Header.Set("Content-Type", "application/json") resp, err := c.Do(req) if err != nil { return errMsg(fmt.Errorf("making request: %s", err)) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) var jsonResp struct { Error string `json:"error"` } json.Unmarshal(body, &jsonResp) if jsonResp.Error != "" { return errMsg(fmt.Errorf("creating card: %s", jsonResp.Error)) } return wordAddedMsg(front) } }