[#38] added lint and used the lint suggestions

This commit is contained in:
Valley 2022-07-09 22:17:41 +08:00 committed by GitHub
parent dfd9528847
commit d64fbf9011
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
36 changed files with 110 additions and 65 deletions

1
.gitignore vendored
View File

@ -1,4 +1,5 @@
/.vscode/ /.vscode/
.idea
.DS_Store .DS_Store

9
Makefile Normal file
View File

@ -0,0 +1,9 @@
lint:
golangci-lint run -c ./golangci.yml ./...
test:
go test -v --cover ./...
test-report:
go test -v --cover -coverprofile=coverage.out ./...
go tool cover -html=coverage.out

View File

@ -66,7 +66,7 @@ func (api *adminApi) refresh(c echo.Context) error {
func (api *adminApi) emailAuth(c echo.Context) error { func (api *adminApi) emailAuth(c echo.Context) error {
form := forms.NewAdminLogin(api.app) form := forms.NewAdminLogin(api.app)
if readErr := c.Bind(form); readErr != nil { if readErr := c.Bind(form); readErr != nil {
return rest.NewBadRequestError("An error occured while reading the submitted data.", readErr) return rest.NewBadRequestError("An error occurred while reading the submitted data.", readErr)
} }
admin, submitErr := form.Submit() admin, submitErr := form.Submit()
@ -80,11 +80,11 @@ func (api *adminApi) emailAuth(c echo.Context) error {
func (api *adminApi) requestPasswordReset(c echo.Context) error { func (api *adminApi) requestPasswordReset(c echo.Context) error {
form := forms.NewAdminPasswordResetRequest(api.app) form := forms.NewAdminPasswordResetRequest(api.app)
if err := c.Bind(form); err != nil { if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("An error occured while reading the submitted data.", err) return rest.NewBadRequestError("An error occurred while reading the submitted data.", err)
} }
if err := form.Validate(); err != nil { if err := form.Validate(); err != nil {
return rest.NewBadRequestError("An error occured while validating the form.", err) return rest.NewBadRequestError("An error occurred while validating the form.", err)
} }
// run in background because we don't need to show the result // run in background because we don't need to show the result
@ -101,7 +101,7 @@ func (api *adminApi) requestPasswordReset(c echo.Context) error {
func (api *adminApi) confirmPasswordReset(c echo.Context) error { func (api *adminApi) confirmPasswordReset(c echo.Context) error {
form := forms.NewAdminPasswordResetConfirm(api.app) form := forms.NewAdminPasswordResetConfirm(api.app)
if readErr := c.Bind(form); readErr != nil { if readErr := c.Bind(form); readErr != nil {
return rest.NewBadRequestError("An error occured while reading the submitted data.", readErr) return rest.NewBadRequestError("An error occurred while reading the submitted data.", readErr)
} }
admin, submitErr := form.Submit() admin, submitErr := form.Submit()

View File

@ -1,13 +1,14 @@
package apis_test package apis_test
import ( import (
"github.com/pocketbase/pocketbase/tests"
"net/http" "net/http"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
"runtime" "runtime"
"testing" "testing"
"github.com/pocketbase/pocketbase/tests"
) )
func TestFileDownload(t *testing.T) { func TestFileDownload(t *testing.T) {

View File

@ -3,8 +3,8 @@ package apis
import ( import (
"net/http" "net/http"
"github.com/pocketbase/dbx"
"github.com/labstack/echo/v5" "github.com/labstack/echo/v5"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/tools/rest" "github.com/pocketbase/pocketbase/tools/rest"

View File

@ -163,11 +163,12 @@ func (api *realtimeApi) bindEvents() {
modelTable := data.Model.TableName() modelTable := data.Model.TableName()
var contextKey string var contextKey string
if modelTable == userTable { switch modelTable {
case userTable:
contextKey = ContextUserKey contextKey = ContextUserKey
} else if modelTable == adminTable { case adminTable:
contextKey = ContextAdminKey contextKey = ContextAdminKey
} else { default:
return nil return nil
} }
@ -186,11 +187,12 @@ func (api *realtimeApi) bindEvents() {
modelTable := data.Model.TableName() modelTable := data.Model.TableName()
var contextKey string var contextKey string
if modelTable == userTable { switch modelTable {
case userTable:
contextKey = ContextUserKey contextKey = ContextUserKey
} else if modelTable == adminTable { case adminTable:
contextKey = ContextAdminKey contextKey = ContextAdminKey
} else { default:
return nil return nil
} }

View File

@ -6,8 +6,8 @@ import (
"net/http" "net/http"
"strings" "strings"
"github.com/pocketbase/dbx"
"github.com/labstack/echo/v5" "github.com/labstack/echo/v5"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos" "github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/forms" "github.com/pocketbase/pocketbase/forms"

View File

@ -41,7 +41,7 @@ func (api *settingsApi) list(c echo.Context) error {
func (api *settingsApi) set(c echo.Context) error { func (api *settingsApi) set(c echo.Context) error {
form := forms.NewSettingsUpsert(api.app) form := forms.NewSettingsUpsert(api.app)
if err := c.Bind(form); err != nil { if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("An error occured while reading the submitted data.", err) return rest.NewBadRequestError("An error occurred while reading the submitted data.", err)
} }
event := &core.SettingsUpdateEvent{ event := &core.SettingsUpdateEvent{
@ -52,7 +52,7 @@ func (api *settingsApi) set(c echo.Context) error {
handlerErr := api.app.OnSettingsBeforeUpdateRequest().Trigger(event, func(e *core.SettingsUpdateEvent) error { handlerErr := api.app.OnSettingsBeforeUpdateRequest().Trigger(event, func(e *core.SettingsUpdateEvent) error {
if err := form.Submit(); err != nil { if err := form.Submit(); err != nil {
return rest.NewBadRequestError("An error occured while submitting the form.", err) return rest.NewBadRequestError("An error occurred while submitting the form.", err)
} }
redactedSettings, err := api.app.Settings().RedactClone() redactedSettings, err := api.app.Settings().RedactClone()

View File

@ -152,7 +152,7 @@ func (api *userApi) authMethods(c echo.Context) error {
func (api *userApi) oauth2Auth(c echo.Context) error { func (api *userApi) oauth2Auth(c echo.Context) error {
form := forms.NewUserOauth2Login(api.app) form := forms.NewUserOauth2Login(api.app)
if readErr := c.Bind(form); readErr != nil { if readErr := c.Bind(form); readErr != nil {
return rest.NewBadRequestError("An error occured while reading the submitted data.", readErr) return rest.NewBadRequestError("An error occurred while reading the submitted data.", readErr)
} }
user, authData, submitErr := form.Submit() user, authData, submitErr := form.Submit()
@ -170,7 +170,7 @@ func (api *userApi) emailAuth(c echo.Context) error {
form := forms.NewUserEmailLogin(api.app) form := forms.NewUserEmailLogin(api.app)
if readErr := c.Bind(form); readErr != nil { if readErr := c.Bind(form); readErr != nil {
return rest.NewBadRequestError("An error occured while reading the submitted data.", readErr) return rest.NewBadRequestError("An error occurred while reading the submitted data.", readErr)
} }
user, submitErr := form.Submit() user, submitErr := form.Submit()
@ -184,11 +184,11 @@ func (api *userApi) emailAuth(c echo.Context) error {
func (api *userApi) requestPasswordReset(c echo.Context) error { func (api *userApi) requestPasswordReset(c echo.Context) error {
form := forms.NewUserPasswordResetRequest(api.app) form := forms.NewUserPasswordResetRequest(api.app)
if err := c.Bind(form); err != nil { if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("An error occured while reading the submitted data.", err) return rest.NewBadRequestError("An error occurred while reading the submitted data.", err)
} }
if err := form.Validate(); err != nil { if err := form.Validate(); err != nil {
return rest.NewBadRequestError("An error occured while validating the form.", err) return rest.NewBadRequestError("An error occurred while validating the form.", err)
} }
// run in background because we don't need to show // run in background because we don't need to show
@ -205,7 +205,7 @@ func (api *userApi) requestPasswordReset(c echo.Context) error {
func (api *userApi) confirmPasswordReset(c echo.Context) error { func (api *userApi) confirmPasswordReset(c echo.Context) error {
form := forms.NewUserPasswordResetConfirm(api.app) form := forms.NewUserPasswordResetConfirm(api.app)
if readErr := c.Bind(form); readErr != nil { if readErr := c.Bind(form); readErr != nil {
return rest.NewBadRequestError("An error occured while reading the submitted data.", readErr) return rest.NewBadRequestError("An error occurred while reading the submitted data.", readErr)
} }
user, submitErr := form.Submit() user, submitErr := form.Submit()
@ -224,7 +224,7 @@ func (api *userApi) requestEmailChange(c echo.Context) error {
form := forms.NewUserEmailChangeRequest(api.app, loggedUser) form := forms.NewUserEmailChangeRequest(api.app, loggedUser)
if err := c.Bind(form); err != nil { if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("An error occured while reading the submitted data.", err) return rest.NewBadRequestError("An error occurred while reading the submitted data.", err)
} }
if err := form.Submit(); err != nil { if err := form.Submit(); err != nil {
@ -237,7 +237,7 @@ func (api *userApi) requestEmailChange(c echo.Context) error {
func (api *userApi) confirmEmailChange(c echo.Context) error { func (api *userApi) confirmEmailChange(c echo.Context) error {
form := forms.NewUserEmailChangeConfirm(api.app) form := forms.NewUserEmailChangeConfirm(api.app)
if readErr := c.Bind(form); readErr != nil { if readErr := c.Bind(form); readErr != nil {
return rest.NewBadRequestError("An error occured while reading the submitted data.", readErr) return rest.NewBadRequestError("An error occurred while reading the submitted data.", readErr)
} }
user, submitErr := form.Submit() user, submitErr := form.Submit()
@ -251,11 +251,11 @@ func (api *userApi) confirmEmailChange(c echo.Context) error {
func (api *userApi) requestVerification(c echo.Context) error { func (api *userApi) requestVerification(c echo.Context) error {
form := forms.NewUserVerificationRequest(api.app) form := forms.NewUserVerificationRequest(api.app)
if err := c.Bind(form); err != nil { if err := c.Bind(form); err != nil {
return rest.NewBadRequestError("An error occured while reading the submitted data.", err) return rest.NewBadRequestError("An error occurred while reading the submitted data.", err)
} }
if err := form.Validate(); err != nil { if err := form.Validate(); err != nil {
return rest.NewBadRequestError("An error occured while validating the form.", err) return rest.NewBadRequestError("An error occurred while validating the form.", err)
} }
// run in background because we don't need to show // run in background because we don't need to show
@ -272,12 +272,12 @@ func (api *userApi) requestVerification(c echo.Context) error {
func (api *userApi) confirmVerification(c echo.Context) error { func (api *userApi) confirmVerification(c echo.Context) error {
form := forms.NewUserVerificationConfirm(api.app) form := forms.NewUserVerificationConfirm(api.app)
if readErr := c.Bind(form); readErr != nil { if readErr := c.Bind(form); readErr != nil {
return rest.NewBadRequestError("An error occured while reading the submitted data.", readErr) return rest.NewBadRequestError("An error occurred while reading the submitted data.", readErr)
} }
user, submitErr := form.Submit() user, submitErr := form.Submit()
if submitErr != nil { if submitErr != nil {
return rest.NewBadRequestError("An error occured while submitting the form.", submitErr) return rest.NewBadRequestError("An error occurred while submitting the form.", submitErr)
} }
return api.authResponse(c, user, nil) return api.authResponse(c, user, nil)

View File

@ -41,11 +41,11 @@ func NewServeCommand(app core.App, showStartBanner bool) *cobra.Command {
} }
// configure cors // configure cors
router.Use(middleware.CORSWithConfig(middleware.CORSConfig(middleware.CORSConfig{ router.Use(middleware.CORSWithConfig(middleware.CORSConfig{
Skipper: middleware.DefaultSkipper, Skipper: middleware.DefaultSkipper,
AllowOrigins: allowedOrigins, AllowOrigins: allowedOrigins,
AllowMethods: []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete}, AllowMethods: []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete},
}))) }))
// ensure that the latest migrations are applied before starting the server // ensure that the latest migrations are applied before starting the server
if err := runMigrations(app); err != nil { if err := runMigrations(app); err != nil {

View File

@ -91,7 +91,7 @@ type App interface {
// entry in the DB, allowing you to modify or validate the stored data. // entry in the DB, allowing you to modify or validate the stored data.
OnModelBeforeCreate() *hook.Hook[*ModelEvent] OnModelBeforeCreate() *hook.Hook[*ModelEvent]
// OnModelAfterCreate hook is triggered after successfuly // OnModelAfterCreate hook is triggered after successfully
// inserting a new entry in the DB. // inserting a new entry in the DB.
OnModelAfterCreate() *hook.Hook[*ModelEvent] OnModelAfterCreate() *hook.Hook[*ModelEvent]
@ -99,7 +99,7 @@ type App interface {
// entry in the DB, allowing you to modify or validate the stored data. // entry in the DB, allowing you to modify or validate the stored data.
OnModelBeforeUpdate() *hook.Hook[*ModelEvent] OnModelBeforeUpdate() *hook.Hook[*ModelEvent]
// OnModelAfterUpdate hook is triggered after successfuly updating // OnModelAfterUpdate hook is triggered after successfully updating
// existing entry in the DB. // existing entry in the DB.
OnModelAfterUpdate() *hook.Hook[*ModelEvent] OnModelAfterUpdate() *hook.Hook[*ModelEvent]
@ -107,7 +107,7 @@ type App interface {
// existing entry from the DB. // existing entry from the DB.
OnModelBeforeDelete() *hook.Hook[*ModelEvent] OnModelBeforeDelete() *hook.Hook[*ModelEvent]
// OnModelAfterDelete is triggered after successfuly deleting an // OnModelAfterDelete is triggered after successfully deleting an
// existing entry from the DB. // existing entry from the DB.
OnModelAfterDelete() *hook.Hook[*ModelEvent] OnModelAfterDelete() *hook.Hook[*ModelEvent]
@ -123,7 +123,7 @@ type App interface {
OnMailerBeforeAdminResetPasswordSend() *hook.Hook[*MailerAdminEvent] OnMailerBeforeAdminResetPasswordSend() *hook.Hook[*MailerAdminEvent]
// OnMailerAfterAdminResetPasswordSend hook is triggered after // OnMailerAfterAdminResetPasswordSend hook is triggered after
// admin password reset email was successfuly sent. // admin password reset email was successfully sent.
OnMailerAfterAdminResetPasswordSend() *hook.Hook[*MailerAdminEvent] OnMailerAfterAdminResetPasswordSend() *hook.Hook[*MailerAdminEvent]
// OnMailerBeforeUserResetPasswordSend hook is triggered right before // OnMailerBeforeUserResetPasswordSend hook is triggered right before
@ -134,7 +134,7 @@ type App interface {
OnMailerBeforeUserResetPasswordSend() *hook.Hook[*MailerUserEvent] OnMailerBeforeUserResetPasswordSend() *hook.Hook[*MailerUserEvent]
// OnMailerAfterUserResetPasswordSend hook is triggered after // OnMailerAfterUserResetPasswordSend hook is triggered after
// a user password reset email was successfuly sent. // a user password reset email was successfully sent.
OnMailerAfterUserResetPasswordSend() *hook.Hook[*MailerUserEvent] OnMailerAfterUserResetPasswordSend() *hook.Hook[*MailerUserEvent]
// OnMailerBeforeUserVerificationSend hook is triggered right before // OnMailerBeforeUserVerificationSend hook is triggered right before
@ -145,7 +145,7 @@ type App interface {
OnMailerBeforeUserVerificationSend() *hook.Hook[*MailerUserEvent] OnMailerBeforeUserVerificationSend() *hook.Hook[*MailerUserEvent]
// OnMailerAfterUserVerificationSend hook is triggered after a user // OnMailerAfterUserVerificationSend hook is triggered after a user
// verification email was successfuly sent. // verification email was successfully sent.
OnMailerAfterUserVerificationSend() *hook.Hook[*MailerUserEvent] OnMailerAfterUserVerificationSend() *hook.Hook[*MailerUserEvent]
// OnMailerBeforeUserChangeEmailSend hook is triggered right before // OnMailerBeforeUserChangeEmailSend hook is triggered right before
@ -156,7 +156,7 @@ type App interface {
OnMailerBeforeUserChangeEmailSend() *hook.Hook[*MailerUserEvent] OnMailerBeforeUserChangeEmailSend() *hook.Hook[*MailerUserEvent]
// OnMailerAfterUserChangeEmailSend hook is triggered after a user // OnMailerAfterUserChangeEmailSend hook is triggered after a user
// change address email was successfuly sent. // change address email was successfully sent.
OnMailerAfterUserChangeEmailSend() *hook.Hook[*MailerUserEvent] OnMailerAfterUserChangeEmailSend() *hook.Hook[*MailerUserEvent]
// --------------------------------------------------------------- // ---------------------------------------------------------------
@ -180,7 +180,7 @@ type App interface {
// Settings API event hooks // Settings API event hooks
// --------------------------------------------------------------- // ---------------------------------------------------------------
// OnSettingsListRequest hook is triggered on each successfull // OnSettingsListRequest hook is triggered on each successful
// API Settings list request. // API Settings list request.
// //
// Could be used to validate or modify the response before // Could be used to validate or modify the response before

View File

@ -5,8 +5,8 @@ package core
import ( import (
"fmt" "fmt"
"github.com/pocketbase/dbx"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
"github.com/pocketbase/dbx"
) )
func connectDB(dbPath string) (*dbx.DB, error) { func connectDB(dbPath string) (*dbx.DB, error) {

View File

@ -360,11 +360,11 @@ func (c AuthProviderConfig) SetupProvider(provider auth.Provider) error {
} }
if c.ClientId != "" { if c.ClientId != "" {
provider.SetClientId(string(c.ClientId)) provider.SetClientId(c.ClientId)
} }
if c.ClientSecret != "" { if c.ClientSecret != "" {
provider.SetClientSecret(string(c.ClientSecret)) provider.SetClientSecret(c.ClientSecret)
} }
if c.AuthUrl != "" { if c.AuthUrl != "" {

View File

@ -166,7 +166,6 @@ func TestDeleteCollection(t *testing.T) {
t.Errorf("(%d) Expected hasErr %v, got %v", i, scenario.expectError, hasErr) t.Errorf("(%d) Expected hasErr %v, got %v", i, scenario.expectError, hasErr)
} }
} }
} }
func TestSaveCollectionCreate(t *testing.T) { func TestSaveCollectionCreate(t *testing.T) {

View File

@ -309,7 +309,7 @@ func (dao *Dao) SyncRecordTableSchema(newCollection *models.Collection, oldColle
newSchema := newCollection.Schema newSchema := newCollection.Schema
// check for renamed table // check for renamed table
if strings.ToLower(oldTableName) != strings.ToLower(newTableName) { if !strings.EqualFold(oldTableName, newTableName) {
_, err := dao.DB().RenameTable(oldTableName, newTableName).Execute() _, err := dao.DB().RenameTable(oldTableName, newTableName).Execute()
if err != nil { if err != nil {
return err return err

View File

@ -396,6 +396,9 @@ func TestSyncRecordTableSchema(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
updatedCollection, err := app.Dao().FindCollectionByNameOrId("demo") updatedCollection, err := app.Dao().FindCollectionByNameOrId("demo")
if err != nil {
t.Fatal(err)
}
updatedCollection.Name = "demo_renamed" updatedCollection.Name = "demo_renamed"
updatedCollection.Schema.RemoveField(updatedCollection.Schema.GetFieldByName("file").Id) updatedCollection.Schema.RemoveField(updatedCollection.Schema.GetFieldByName("file").Id)
updatedCollection.Schema.AddField( updatedCollection.Schema.AddField(

View File

@ -107,7 +107,7 @@ func TestAdminPasswordResetConfirmSubmit(t *testing.T) {
} }
claims, _ := security.ParseUnverifiedJWT(s.token) claims, _ := security.ParseUnverifiedJWT(s.token)
tokenAdminId, _ := claims["id"] tokenAdminId := claims["id"]
if admin.Id != tokenAdminId { if admin.Id != tokenAdminId {
t.Errorf("(%d) Expected admin with id %s to be returned, got %v", i, tokenAdminId, admin) t.Errorf("(%d) Expected admin with id %s to be returned, got %v", i, tokenAdminId, admin)

View File

@ -95,7 +95,7 @@ func (form *CollectionUpsert) checkUniqueName(value any) error {
return validation.NewError("validation_collection_name_exists", "Collection name must be unique (case insensitive).") return validation.NewError("validation_collection_name_exists", "Collection name must be unique (case insensitive).")
} }
if (form.isCreate || strings.ToLower(v) != strings.ToLower(form.collection.Name)) && form.app.Dao().HasTable(v) { if (form.isCreate || !strings.EqualFold(v, form.collection.Name)) && form.app.Dao().HasTable(v) {
return validation.NewError("validation_collection_name_table_exists", "The collection name must be also unique table name.") return validation.NewError("validation_collection_name_table_exists", "The collection name must be also unique table name.")
} }

View File

@ -44,7 +44,6 @@ func NewRecordUpsert(app core.App, record *models.Record) *RecordUpsert {
form.Data = map[string]any{} form.Data = map[string]any{}
for _, field := range record.Collection().Schema.Fields() { for _, field := range record.Collection().Schema.Fields() {
form.Data[field.Name] = record.GetDataValue(field.Name) form.Data[field.Name] = record.GetDataValue(field.Name)
} }
return form return form
@ -147,7 +146,7 @@ func (form *RecordUpsert) LoadData(r *http.Request) error {
for _, field := range form.record.Collection().Schema.Fields() { for _, field := range form.record.Collection().Schema.Fields() {
key := field.Name key := field.Name
value, _ := extendedData[key] value := extendedData[key]
value = field.PrepareValue(value) value = field.PrepareValue(value)
if field.Type == schema.FieldTypeFile { if field.Type == schema.FieldTypeFile {

View File

@ -29,7 +29,7 @@ func TestNewRecordUpsert(t *testing.T) {
form := forms.NewRecordUpsert(app, record) form := forms.NewRecordUpsert(app, record)
val, _ := form.Data["title"] val := form.Data["title"]
if val != "test_value" { if val != "test_value" {
t.Errorf("Expected record data to be load, got %v", form.Data) t.Errorf("Expected record data to be load, got %v", form.Data)
} }

View File

@ -68,7 +68,7 @@ func (form *UserOauth2Login) Submit() (*models.User, *auth.AuthUser, error) {
return nil, nil, err return nil, nil, err
} }
config, _ := form.app.Settings().NamedAuthProviderConfigs()[form.Provider] config := form.app.Settings().NamedAuthProviderConfigs()[form.Provider]
config.SetupProvider(provider) config.SetupProvider(provider)
provider.SetRedirectUrl(form.RedirectUrl) provider.SetRedirectUrl(form.RedirectUrl)

View File

@ -148,7 +148,7 @@ func TestUserPasswordResetConfirmSubmit(t *testing.T) {
} }
claims, _ := security.ParseUnverifiedJWT(form.Token) claims, _ := security.ParseUnverifiedJWT(form.Token)
tokenUserId, _ := claims["id"] tokenUserId := claims["id"]
if user.Id != tokenUserId { if user.Id != tokenUserId {
t.Errorf("(%d) Expected user with id %s, got %v", i, tokenUserId, user) t.Errorf("(%d) Expected user with id %s, got %v", i, tokenUserId, user)

View File

@ -127,7 +127,7 @@ func TestUserVerificationConfirmSubmit(t *testing.T) {
} }
claims, _ := security.ParseUnverifiedJWT(form.Token) claims, _ := security.ParseUnverifiedJWT(form.Token)
tokenUserId, _ := claims["id"] tokenUserId := claims["id"]
if user.Id != tokenUserId { if user.Id != tokenUserId {
t.Errorf("(%d) Expected user.Id %q, got %q", i, tokenUserId, user.Id) t.Errorf("(%d) Expected user.Id %q, got %q", i, tokenUserId, user.Id)

View File

@ -6,9 +6,9 @@ import (
"regexp" "regexp"
"strings" "strings"
"github.com/pocketbase/dbx"
validation "github.com/go-ozzo/ozzo-validation/v4" validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is" "github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos" "github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/models" "github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/models/schema" "github.com/pocketbase/pocketbase/models/schema"

View File

@ -1189,7 +1189,7 @@ func TestRecordDataValidatorValidateRelation(t *testing.T) {
Type: schema.FieldTypeRelation, Type: schema.FieldTypeRelation,
Options: &schema.RelationOptions{ Options: &schema.RelationOptions{
MaxSelect: 3, MaxSelect: 3,
CollectionId: "", // missing or nonexisting colleciton id CollectionId: "", // missing or non-existing collection id
}, },
}, },
) )

30
golangci.yml Normal file
View File

@ -0,0 +1,30 @@
run:
go: 1.18
concurrency: 4
timeout: 10m
linters:
disable-all: true
enable:
- asciicheck
- deadcode
- depguard
- exportloopref
- gocritic
- gofmt
- goimports
- gomodguard
- goprintffuncname
- gosimple
- govet
- ineffassign
- misspell
- nakedret
- nolintlint
- prealloc
- staticcheck
- typecheck
- unconvert
- unused
- varcheck
- whitespace

View File

@ -134,7 +134,7 @@ func (s *Schema) AddField(newField *SchemaField) {
// checks for invalid renamed fields and field name duplications. // checks for invalid renamed fields and field name duplications.
func (s Schema) Validate() error { func (s Schema) Validate() error {
return validation.Validate(&s.fields, validation.Required, validation.By(func(value any) error { return validation.Validate(&s.fields, validation.Required, validation.By(func(value any) error {
fields := s.fields // use directly the schema value to avoid unnecesary interface casting fields := s.fields // use directly the schema value to avoid unnecessary interface casting
if len(fields) == 0 { if len(fields) == 0 {
return validation.NewError("validation_invalid_schema", "Invalid schema format.") return validation.NewError("validation_invalid_schema", "Invalid schema format.")

View File

@ -493,9 +493,9 @@ func TestSchemaFieldPrepareValue(t *testing.T) {
value any value any
expectJson string expectJson string
}{ }{
{schema.SchemaField{Type: "unkown"}, "test", `"test"`}, {schema.SchemaField{Type: "unknown"}, "test", `"test"`},
{schema.SchemaField{Type: "unkown"}, 123, "123"}, {schema.SchemaField{Type: "unknown"}, 123, "123"},
{schema.SchemaField{Type: "unkown"}, []int{1, 2, 1}, "[1,2,1]"}, {schema.SchemaField{Type: "unknown"}, []int{1, 2, 1}, "[1,2,1]"},
// text // text
{schema.SchemaField{Type: schema.FieldTypeText}, nil, `null`}, {schema.SchemaField{Type: schema.FieldTypeText}, nil, `null`},
@ -1281,7 +1281,6 @@ func TestFileOptionsValidate(t *testing.T) {
} }
func TestRelationOptionsValidate(t *testing.T) { func TestRelationOptionsValidate(t *testing.T) {
scenarios := []fieldOptionsScenario{ scenarios := []fieldOptionsScenario{
{ {
"empty", "empty",

View File

@ -109,7 +109,7 @@ func (scenario *ApiScenario) Test(t *testing.T) {
} }
for event, expectedCalls := range scenario.ExpectedEvents { for event, expectedCalls := range scenario.ExpectedEvents {
actualCalls, _ := testApp.EventCalls[event] actualCalls := testApp.EventCalls[event]
if actualCalls != expectedCalls { if actualCalls != expectedCalls {
t.Errorf("[%s] Expected event %s to be called %d, got %d", prefix, event, expectedCalls, actualCalls) t.Errorf("[%s] Expected event %s to be called %d, got %d", prefix, event, expectedCalls, actualCalls)
} }

View File

@ -1,4 +1,4 @@
// Pacakge tests provides common helpers and mocks used in PocketBase application tests. // Package tests provides common helpers and mocks used in PocketBase application tests.
package tests package tests
import ( import (

View File

@ -127,7 +127,7 @@ func (s *System) DeletePrefix(prefix string) []error {
Prefix: prefix, Prefix: prefix,
} }
// delete all files witht the prefix // delete all files with the prefix
// --- // ---
iter := s.bucket.List(&opts) iter := s.bucket.List(&opts)
for { for {

View File

@ -82,7 +82,7 @@ func TestSanitize(t *testing.T) {
{" ", ` `, "", false}, {" ", ` `, "", false},
{"", `[A-Z]`, "", false}, {"", `[A-Z]`, "", false},
{"abcABC", `[A-Z]`, "abc", false}, {"abcABC", `[A-Z]`, "abc", false},
{"abcABC", `[A-Z`, "", true}, // invlid pattern {"abcABC", `[A-Z`, "", true}, // invalid pattern
} }
for i, scenario := range scenarios { for i, scenario := range scenarios {

View File

@ -210,7 +210,7 @@ func (s *Provider) Exec(items any) (*Result, error) {
s.perPage = MaxPerPage s.perPage = MaxPerPage
} }
// normalize page accoring to the total count // normalize page according to the total count
if s.page <= 0 || totalCount == 0 { if s.page <= 0 || totalCount == 0 {
s.page = 1 s.page = 1
} else if totalPages := int(math.Ceil(float64(totalCount) / float64(s.perPage))); s.page > totalPages { } else if totalPages := int(math.Ceil(float64(totalCount) / float64(s.perPage))); s.page > totalPages {

View File

@ -9,6 +9,7 @@ import (
func TestRandomString(t *testing.T) { func TestRandomString(t *testing.T) {
generated := []string{} generated := []string{}
reg := regexp.MustCompile(`[a-zA-Z0-9]+`)
for i := 0; i < 30; i++ { for i := 0; i < 30; i++ {
length := 5 + i length := 5 + i
@ -18,7 +19,7 @@ func TestRandomString(t *testing.T) {
t.Errorf("(%d) Expected the length of the string to be %d, got %d", i, length, len(result)) t.Errorf("(%d) Expected the length of the string to be %d, got %d", i, length, len(result))
} }
if match, _ := regexp.MatchString("[a-zA-Z0-9]+", result); !match { if match := reg.MatchString(result); !match {
t.Errorf("(%d) The generated strings should have only [a-zA-Z0-9]+ characters, got %q", i, result) t.Errorf("(%d) The generated strings should have only [a-zA-Z0-9]+ characters, got %q", i, result)
} }

View File

@ -1,10 +1,11 @@
package types_test package types_test
import ( import (
"github.com/pocketbase/pocketbase/tools/types"
"strings" "strings"
"testing" "testing"
"time" "time"
"github.com/pocketbase/pocketbase/tools/types"
) )
func TestNowDateTime(t *testing.T) { func TestNowDateTime(t *testing.T) {

View File

@ -13,8 +13,8 @@ var distDir embed.FS
//go:embed dist/index.html //go:embed dist/index.html
var indexHTML embed.FS var indexHTML embed.FS
// DistDirFS contains the embeded dist directory files (without the "dist" prefix) // DistDirFS contains the embedded dist directory files (without the "dist" prefix)
var DistDirFS = echo.MustSubFS(distDir, "dist") var DistDirFS = echo.MustSubFS(distDir, "dist")
// DistIndexHTML contains the embeded dist/index.html file (without the "dist" prefix) // DistIndexHTML contains the embedded dist/index.html file (without the "dist" prefix)
var DistIndexHTML = echo.MustSubFS(indexHTML, "dist") var DistIndexHTML = echo.MustSubFS(indexHTML, "dist")