~sircmpwn/meta.sr.ht

ref: 0.56.17 meta.sr.ht/api/graph/model/invoice.go -rw-r--r-- 2.0 KiB
b1deacf0Nicolas Schodet Fix field name when validating the PGP key in RegisterAccount 11 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package model

import (
	"context"
	"database/sql"
	"strconv"
	"time"

	sq "github.com/Masterminds/squirrel"

	"git.sr.ht/~sircmpwn/core-go/database"
	"git.sr.ht/~sircmpwn/core-go/model"
)

type Invoice struct {
	ID        int       `json:"id"`
	Created   time.Time `json:"created"`
	Cents     int       `json:"cents"`
	ValidThru time.Time `json:"validThru"`
	Source    *string   `json:"source"`

	UserID int

	alias  string
	fields *database.ModelFields
}

func (inv *Invoice) As(alias string) *Invoice {
	inv.alias = alias
	return inv
}

func (i *Invoice) Alias() string {
	return i.alias
}

func (i *Invoice) Table() string {
	return "invoice"
}

func (i *Invoice) Fields() *database.ModelFields {
	if i.fields != nil {
		return i.fields
	}
	i.fields = &database.ModelFields{
		Fields: []*database.FieldMap{
			{ "id", "id", &i.ID },
			{ "created", "created", &i.Created },
			{ "cents", "cents", &i.Cents },
			{ "valid_thru", "validThru", &i.ValidThru },
			{ "source", "source", &i.Source },

			// Always fetch:
			{ "id", "", &i.ID },
			{ "user_id", "", &i.UserID },
		},
	}
	return i.fields
}

func (inv *Invoice) QueryWithCursor(ctx context.Context, runner sq.BaseRunner,
	q sq.SelectBuilder, cur *model.Cursor) ([]*Invoice, *model.Cursor) {
	var (
		err  error
		rows *sql.Rows
	)

	if cur.Next != "" {
		next, _ := strconv.ParseInt(cur.Next, 10, 64)
		q = q.Where(database.WithAlias(inv.alias, "id")+"<= ?", next)
	}
	q = q.
		OrderBy(database.WithAlias(inv.alias, "id")).
		Limit(uint64(cur.Count + 1))

	if rows, err = q.RunWith(runner).QueryContext(ctx); err != nil {
		panic(err)
	}
	defer rows.Close()

	var invoices []*Invoice
	for rows.Next() {
		var inv Invoice
		if err := rows.Scan(database.Scan(ctx, &inv)...); err != nil {
			panic(err)
		}
		invoices = append(invoices, &inv)
	}

	if len(invoices) > cur.Count {
		cur = &model.Cursor{
			Count:  cur.Count,
			Next:   strconv.Itoa(invoices[len(invoices)-1].ID),
			Search: cur.Search,
		}
		invoices = invoices[:cur.Count]
	} else {
		cur = nil
	}

	return invoices, cur
}