[#3273] added readerToString() JSVM helper
This commit is contained in:
@@ -33,6 +33,7 @@ import (
|
||||
"github.com/pocketbase/pocketbase/tools/inflector"
|
||||
"github.com/pocketbase/pocketbase/tools/list"
|
||||
"github.com/pocketbase/pocketbase/tools/mailer"
|
||||
"github.com/pocketbase/pocketbase/tools/rest"
|
||||
"github.com/pocketbase/pocketbase/tools/security"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
"github.com/spf13/cobra"
|
||||
@@ -278,6 +279,21 @@ func wrapMiddlewares(executors *vmsPool, rawMiddlewares ...goja.Value) ([]echo.M
|
||||
func baseBinds(vm *goja.Runtime) {
|
||||
vm.SetFieldNameMapper(FieldMapper{})
|
||||
|
||||
vm.Set("readerToString", func(r io.Reader, maxBytes int) (string, error) {
|
||||
if maxBytes == 0 {
|
||||
maxBytes = rest.DefaultMaxMemory
|
||||
}
|
||||
|
||||
limitReader := io.LimitReader(r, int64(maxBytes))
|
||||
|
||||
bodyBytes, readErr := io.ReadAll(limitReader)
|
||||
if readErr != nil {
|
||||
return "", readErr
|
||||
}
|
||||
|
||||
return string(bodyBytes), nil
|
||||
})
|
||||
|
||||
vm.Set("arrayOf", func(model any) any {
|
||||
mt := reflect.TypeOf(model)
|
||||
st := reflect.SliceOf(mt)
|
||||
|
||||
@@ -46,7 +46,27 @@ func TestBaseBindsCount(t *testing.T) {
|
||||
vm := goja.New()
|
||||
baseBinds(vm)
|
||||
|
||||
testBindsCount(vm, "this", 13, t)
|
||||
testBindsCount(vm, "this", 14, t)
|
||||
}
|
||||
|
||||
func TestBaseBindsReaderToString(t *testing.T) {
|
||||
app, _ := tests.NewTestApp()
|
||||
defer app.Cleanup()
|
||||
|
||||
vm := goja.New()
|
||||
baseBinds(vm)
|
||||
vm.Set("reader", strings.NewReader("test"))
|
||||
|
||||
_, err := vm.RunString(`
|
||||
let result = readerToString(reader)
|
||||
|
||||
if (result != "test") {
|
||||
throw new Error('Expected "test", got ' + result);
|
||||
}
|
||||
`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseBindsRecord(t *testing.T) {
|
||||
|
||||
+3852
-3834
File diff suppressed because it is too large
Load Diff
@@ -180,6 +180,24 @@ declare var $app: appWithoutHooks
|
||||
*/
|
||||
declare var $template: template.Registry
|
||||
|
||||
/**
|
||||
* readerToString reads the content of the specified io.Reader until
|
||||
* EOF or maxBytes are reached.
|
||||
*
|
||||
* If maxBytes is not specified it will read up to 32MB.
|
||||
*
|
||||
* Note that after this call the reader can't be used anymore.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* ` + "```" + `js
|
||||
* const rawBody = readerToString(c.request().body)
|
||||
* ` + "```" + `
|
||||
*
|
||||
* @group PocketBase
|
||||
*/
|
||||
declare function readerToString(reader: any, maxBytes?: number): string;
|
||||
|
||||
/**
|
||||
* arrayOf creates a placeholder array of the specified models.
|
||||
* Usually used to populate DB result into an array of models.
|
||||
|
||||
Reference in New Issue
Block a user