[#3273] added readerToString() JSVM helper

This commit is contained in:
Gani Georgiev
2023-09-10 10:46:19 +03:00
parent b2c8f394af
commit 0ca86a0c87
38 changed files with 3956 additions and 3877 deletions
+16
View File
@@ -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)
+21 -1
View File
@@ -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) {
File diff suppressed because it is too large Load Diff
+18
View File
@@ -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.