API: Rig up file { contents }

This commit is contained in:
Drew DeVault 2021-09-21 11:57:17 +02:00
parent ec9bcf7fae
commit fa643487fd
2 changed files with 52 additions and 4 deletions

View File

@ -7,8 +7,10 @@ import (
"context"
"database/sql"
"fmt"
"net/url"
"git.sr.ht/~sircmpwn/core-go/auth"
"git.sr.ht/~sircmpwn/core-go/config"
"git.sr.ht/~sircmpwn/core-go/database"
coremodel "git.sr.ht/~sircmpwn/core-go/model"
"git.sr.ht/~sircmpwn/paste.sr.ht/api/graph/api"
@ -27,7 +29,17 @@ func (r *fileResolver) Sha(ctx context.Context, obj *model.File) (string, error)
}
func (r *fileResolver) Contents(ctx context.Context, obj *model.File) (*model.URL, error) {
panic(fmt.Errorf("not implemented"))
blob, err := loaders.ForContext(ctx).BlobsByID.Load(obj.BlobID)
if err != nil {
panic(err)
}
origin := config.GetOrigin(config.ForContext(ctx), "paste.sr.ht", true)
uri := fmt.Sprintf("%s/query/blob/%s", origin, blob.SHA)
url, err := url.Parse(uri)
if err != nil {
panic(err)
}
return &model.URL{url}, nil
}
func (r *mutationResolver) Create(ctx context.Context, files []*graphql.Upload, visibility model.Visibility) (*model.Paste, error) {

View File

@ -2,10 +2,14 @@ package main
import (
"context"
"net/http"
"database/sql"
"git.sr.ht/~sircmpwn/core-go/config"
"git.sr.ht/~sircmpwn/core-go/database"
"git.sr.ht/~sircmpwn/core-go/server"
"github.com/99designs/gqlgen/graphql"
"github.com/go-chi/chi"
"git.sr.ht/~sircmpwn/paste.sr.ht/api/graph"
"git.sr.ht/~sircmpwn/paste.sr.ht/api/graph/api"
@ -29,9 +33,41 @@ func main() {
scopes[i] = s.String()
}
server.NewServer("paste.sr.ht", appConfig).
gsrv := server.NewServer("paste.sr.ht", appConfig).
WithDefaultMiddleware().
WithMiddleware(loaders.Middleware).
WithSchema(schema, scopes).
Run()
WithSchema(schema, scopes)
// Bulk transfer endpoints
gsrv.Router().Get("/query/blob/{id}", func(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
if err := database.WithTx(r.Context(), &sql.TxOptions{
Isolation: 0,
ReadOnly: true,
}, func(tx *sql.Tx) error {
var data []byte
row := tx.QueryRowContext(r.Context(), `
SELECT contents
FROM blob
WHERE sha = $1;
`, id)
if err := row.Scan(&data); err != nil {
return err
}
_, err := w.Write(data)
return err
}); err != nil {
if err == sql.ErrNoRows {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("Blob not found\r\n"))
return
} else {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("Blob not found\r\n"))
return
}
}
})
gsrv.Run()
}