Skip to content

Commit

Permalink
Bump to convex 1.3.1 and add format param to api calls (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
nipunn1313 authored Oct 18, 2023
1 parent 35783ca commit 422634e
Show file tree
Hide file tree
Showing 21 changed files with 809 additions and 1,094 deletions.
3 changes: 2 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
FROM --platform=$BUILDPLATFORM cgr.dev/chainguard/go:1.20 as build
FROM --platform=$BUILDPLATFORM cgr.dev/chainguard/wolfi-base as build
RUN apk update && apk add build-base git openssh go-1.20

WORKDIR /work

Expand Down
33 changes: 17 additions & 16 deletions convex.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/fs"
"net/http"
"time"
Expand All @@ -18,18 +19,17 @@ type LinkDocument struct {
Owner string `json:"owner"`
}

type StatsMap struct {
Stats [][2]interface{} `json:"$map"`
}
type StatsMap = map[string]interface{}

type ConvexDB struct {
url string
token string
}

type UdfExecution struct {
Path string `json:"path"`
Args []interface{} `json:"args"`
Path string `json:"path"`
Args map[string]interface{} `json:"args"`
Format string `json:"format"`
}

type ConvexResponse struct {
Expand All @@ -43,7 +43,7 @@ func NewConvexDB(url string, token string) *ConvexDB {
}

func (c *ConvexDB) mutation(args *UdfExecution) error {
args.Args = append(args.Args, c.token)
args.Args["token"] = c.token
url := fmt.Sprintf("%s/api/mutation", c.url)
encodedArgs, err := json.Marshal(args)
if err != nil {
Expand Down Expand Up @@ -73,7 +73,7 @@ func (c *ConvexDB) mutation(args *UdfExecution) error {
}

func (c *ConvexDB) query(args *UdfExecution) (json.RawMessage, error) {
args.Args = append(args.Args, c.token)
args.Args["token"] = c.token
url := fmt.Sprintf("%s/api/query", c.url)
encodedArgs, err := json.Marshal(args)
if err != nil {
Expand All @@ -84,7 +84,8 @@ func (c *ConvexDB) query(args *UdfExecution) (json.RawMessage, error) {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("unexpected status code from Convex: %d", resp.StatusCode)
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("unexpected status code from Convex: %d: %s", resp.StatusCode, body)
}

defer resp.Body.Close()
Expand All @@ -103,7 +104,7 @@ func (c *ConvexDB) query(args *UdfExecution) (json.RawMessage, error) {
}

func (c *ConvexDB) LoadAll() ([]*Link, error) {
args := UdfExecution{"load:loadAll", []interface{}{}}
args := UdfExecution{"load:loadAll", map[string]interface{}{}, "json"}
resp, err := c.query(&args)
if err != nil {
return nil, err
Expand All @@ -130,7 +131,7 @@ func (c *ConvexDB) LoadAll() ([]*Link, error) {
}

func (c *ConvexDB) Load(short string) (*Link, error) {
args := UdfExecution{"load:loadOne", []interface{}{linkID(short)}}
args := UdfExecution{"load:loadOne", map[string]interface{}{"normalizedId": linkID(short)}, "json"}
resp, err := c.query(&args)
if err != nil {
return nil, err
Expand Down Expand Up @@ -166,12 +167,12 @@ func (c *ConvexDB) Save(link *Link) error {
LastEdit: float64(link.LastEdit.Unix()),
Owner: link.Owner,
}
args := UdfExecution{"store", []interface{}{document}}
args := UdfExecution{"store", map[string]interface{}{"link": document}, "json"}
return c.mutation(&args)
}

func (c *ConvexDB) LoadStats() (ClickStats, error) {
args := UdfExecution{"stats:loadStats", []interface{}{}}
args := UdfExecution{"stats:loadStats", map[string]interface{}{}, "json"}
response, err := c.query(&args)
if err != nil {
return nil, err
Expand All @@ -184,12 +185,12 @@ func (c *ConvexDB) LoadStats() (ClickStats, error) {
return nil, err
}
clicks := make(ClickStats)
for _, entry := range stats.Stats {
num, err := entry[1].(json.Number).Float64()
for k, v := range stats {
num, err := v.(json.Number).Float64()
if err != nil {
return nil, err
}
clicks[entry[0].(string)] = int(num)
clicks[k] = int(num)
}
return clicks, nil
}
Expand All @@ -199,6 +200,6 @@ func (c *ConvexDB) SaveStats(stats ClickStats) error {
for id, clicks := range stats {
mungedStats[linkID(id)] = clicks
}
args := UdfExecution{"stats:saveStats", []interface{}{mungedStats}}
args := UdfExecution{"stats:saveStats", map[string]interface{}{"stats": mungedStats}, "json"}
return c.mutation(&args)
}
6 changes: 1 addition & 5 deletions convex.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
{
"project": "golink",
"team": "convex",
"prodUrl": "https://merry-grouse-70.convex.cloud",
"functions": "src/convex/",
"authInfo": []
"functions": "src/convex/"
}
22 changes: 18 additions & 4 deletions convex_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,29 @@ import (

"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/joho/godotenv"
)

func clear(c *ConvexDB) {
c.mutation(&UdfExecution{Path: "clear", Args: []interface{}{}})
c.mutation(&UdfExecution{Path: "clear", Args: map[string]interface{}{}, Format: "json"})
}

func getDbUrl() string {
envLocal, err := godotenv.Read(".env.local")
if err != nil {
return "https://feeble-gull-946.convex.cloud"
}
url := envLocal["VITE_CONVEX_URL"]
if len(url) == 0 {
url = "https://feeble-gull-946.convex.cloud"
}
return url
}

// Test saving and loading links for SQLiteDB
func Test_Convex_SaveLoadLinks(t *testing.T) {
db := NewConvexDB("https://feeble-gull-946.convex.cloud", "test")
url := getDbUrl()
db := NewConvexDB(url, "test")
clear(db)
defer clear(db)

Expand Down Expand Up @@ -56,11 +70,11 @@ func Test_Convex_SaveLoadLinks(t *testing.T) {

// Test saving and loading stats for SQLiteDB
func Test_Convex_SaveLoadStats(t *testing.T) {
db := NewConvexDB("https://feeble-gull-946.convex.cloud", "test")
url := getDbUrl()
db := NewConvexDB(url, "test")
clear(db)
defer clear(db)


// preload some links
links := []*Link{
{Short: "a"},
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ require (
github.com/illarion/gonotify v1.0.1 // indirect
github.com/insomniacslk/dhcp v0.0.0-20221215072855-de60144f33f8 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/joho/godotenv v1.5.1 // indirect
github.com/josharian/native v1.1.1-0.20230202152459-5c7d0dd6ab86 // indirect
github.com/jsimonetti/rtnetlink v1.1.2-0.20220408201609-d380b505068b // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9Y
github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8=
github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/josharian/native v1.0.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w=
github.com/josharian/native v1.0.1-0.20221213033349-c1e37c09b531/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w=
github.com/josharian/native v1.1.1-0.20230202152459-5c7d0dd6ab86 h1:elKwZS1OcdQ0WwEDBeqxKwb7WB62QX8bvZ/FJnVXIfk=
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@
"typescript": "^4.9.5"
},
"dependencies": {
"convex": "^0.9.1"
"convex": "^1.3.1"
}
}
33 changes: 22 additions & 11 deletions src/convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,43 @@
/* eslint-disable */
/**
* Generated API.
* Generated `api` utility.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* Generated by convex@0.9.1.
* To regenerate, run `npx convex codegen`.
* Generated by convex@1.3.1.
* To regenerate, run `npx convex dev`.
* @module
*/

import type { ApiFromModules } from "convex/api";
import type {
ApiFromModules,
FilterApi,
FunctionReference,
} from "convex/server";
import type * as clear from "../clear";
import type * as load from "../load";
import type * as stats from "../stats";
import type * as store from "../store";

/**
* A type describing your app's public Convex API.
* A utility for referencing Convex functions in your app's API.
*
* This `API` type includes information about the arguments and return
* types of your app's query and mutation functions.
*
* This type should be used with type-parameterized classes like
* `ConvexReactClient` to create app-specific types.
* Usage:
* ```js
* const myFunctionReference = api.myModule.myFunction;
* ```
*/
export type API = ApiFromModules<{
declare const fullApi: ApiFromModules<{
clear: typeof clear;
load: typeof load;
stats: typeof stats;
store: typeof store;
}>;
export declare const api: FilterApi<
typeof fullApi,
FunctionReference<any, "public">
>;
export declare const internal: FilterApi<
typeof fullApi,
FunctionReference<any, "internal">
>;
23 changes: 23 additions & 0 deletions src/convex/_generated/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/* eslint-disable */
/**
* Generated `api` utility.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* Generated by [email protected].
* To regenerate, run `npx convex dev`.
* @module
*/

import { anyApi } from "convex/server";

/**
* A utility for referencing Convex functions in your app's API.
*
* Usage:
* ```js
* const myFunctionReference = api.myModule.myFunction;
* ```
*/
export const api = anyApi;
export const internal = anyApi;
29 changes: 7 additions & 22 deletions src/convex/_generated/dataModel.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* Generated by convex@0.9.1.
* To regenerate, run `npx convex codegen`.
* Generated by convex@1.3.1.
* To regenerate, run `npx convex dev`.
* @module
*/

import type { DataModelFromSchemaDefinition } from "convex/schema";
import type { DataModelFromSchemaDefinition } from "convex/server";
import type { DocumentByName, TableNamesInDataModel } from "convex/server";
import { GenericId, GenericIdConstructor } from "convex/values";
import type { GenericId } from "convex/values";
import schema from "../schema";

/**
Expand All @@ -24,7 +24,7 @@ export type TableNames = TableNamesInDataModel<DataModel>;
*
* @typeParam TableName - A string literal type of the table name (like "users").
*/
export type Document<TableName extends TableNames> = DocumentByName<
export type Doc<TableName extends TableNames> = DocumentByName<
DataModel,
TableName
>;
Expand All @@ -37,28 +37,13 @@ export type Document<TableName extends TableNames> = DocumentByName<
*
* Documents can be loaded using `db.get(id)` in query and mutation functions.
*
* **Important**: Use `myId.equals(otherId)` to check for equality.
* Using `===` will not work because two different instances of `Id` can refer
* to the same document.
* IDs are just strings at runtime, but this type can be used to distinguish them from other
* strings when type checking.
*
* @typeParam TableName - A string literal type of the table name (like "users").
*/
export type Id<TableName extends TableNames> = GenericId<TableName>;

/**
* An identifier for a document in Convex.
*
* Convex documents are uniquely identified by their `Id`, which is accessible
* on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
*
* Documents can be loaded using `db.get(id)` in query and mutation functions.
*
* **Important**: Use `myId.equals(otherId)` to check for equality.
* Using `===` will not work because two different instances of `Id` can refer
* to the same document.
*/
export declare const Id: GenericIdConstructor<TableNames>;

/**
* A type describing your Convex data model.
*
Expand Down
26 changes: 0 additions & 26 deletions src/convex/_generated/dataModel.js

This file was deleted.

Loading

0 comments on commit 422634e

Please sign in to comment.