fix linter errors

This commit is contained in:
Hayden 2022-09-03 01:52:05 -08:00
parent 39d8ff03f8
commit b33ef5f029
14 changed files with 44 additions and 307 deletions

View file

@ -31,7 +31,7 @@ func userPool() func() {
users = userOut
purge := func() {
mockHandler.svc.Admin.DeleteAll(context.Background())
_ = mockHandler.svc.Admin.DeleteAll(context.Background())
}
return purge
@ -43,7 +43,9 @@ func TestMain(m *testing.M) {
repos, closeDb := mocks.GetEntRepos()
mockHandler.svc = mocks.GetMockServices(repos)
defer closeDb()
defer func() {
_ = closeDb()
}()
purge := userPool()
defer purge()

View file

@ -1,55 +0,0 @@
package main
import (
"time"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/internal/types"
"github.com/hay-kot/content/backend/pkgs/automapper"
"github.com/tkrajina/typescriptify-golang-structs/typescriptify"
)
// generateMappers serialized the config file into a list of automapper struct
func generateMappers() []automapper.AutoMapper {
return []automapper.AutoMapper{}
}
func generateTypeScript() {
// Configuration
converter := typescriptify.New()
converter.CreateInterface = true
converter.ManageType(uuid.UUID{}, typescriptify.TypeOptions{TSType: "string"})
converter.ManageType(time.Time{}, typescriptify.TypeOptions{TSType: "Date", TSTransform: "new Date(__VALUE__)"})
// General
public := []any{
// Base Types
types.ApiSummary{},
// User Types
types.UserCreate{},
types.UserIn{},
types.UserUpdate{},
// Auth Types
types.LoginForm{},
types.TokenResponse{},
}
for i := 0; i < len(public); i++ {
converter.Add(public[i])
}
// Creation
converter.ConvertToFile("./generated-types.ts")
}
func main() {
automappers := generateMappers()
conf := automapper.DefaultConf()
automapper.Generate(automappers, conf)
generateTypeScript()
}

View file

@ -27,7 +27,8 @@ func Test_Locations_Get(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, loc.ID, foundLoc.ID)
testRepos.Locations.Delete(context.Background(), loc.ID)
err = testRepos.Locations.Delete(context.Background(), loc.ID)
assert.NoError(t, err)
}
func Test_LocationsGetAllWithCount(t *testing.T) {
@ -36,8 +37,9 @@ func Test_LocationsGetAllWithCount(t *testing.T) {
Name: fk.RandomString(10),
Description: fk.RandomString(100),
})
assert.NoError(t, err)
testRepos.Items.Create(ctx, testGroup.ID, types.ItemCreate{
_, err = testRepos.Items.Create(ctx, testGroup.ID, types.ItemCreate{
Name: fk.RandomString(10),
Description: fk.RandomString(100),
LocationID: result.ID,
@ -65,7 +67,8 @@ func Test_Locations_Create(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, loc.ID, foundLoc.ID)
testRepos.Locations.Delete(context.Background(), loc.ID)
err = testRepos.Locations.Delete(context.Background(), loc.ID)
assert.NoError(t, err)
}
func Test_Locations_Update(t *testing.T) {
@ -88,7 +91,8 @@ func Test_Locations_Update(t *testing.T) {
assert.Equal(t, update.Name, foundLoc.Name)
assert.Equal(t, update.Description, foundLoc.Description)
testRepos.Locations.Delete(context.Background(), loc.ID)
err = testRepos.Locations.Delete(context.Background(), loc.ID)
assert.NoError(t, err)
}
func Test_Locations_Delete(t *testing.T) {

View file

@ -34,8 +34,9 @@ func Test_EntAuthTokenRepo_CreateToken(t *testing.T) {
assert.Equal(expiresAt, token.ExpiresAt)
// Cleanup
testRepos.Users.Delete(ctx, userOut.ID)
testRepos.AuthTokens.DeleteAll(ctx)
assert.NoError(testRepos.Users.Delete(ctx, userOut.ID))
_, err = testRepos.AuthTokens.DeleteAll(ctx)
assert.NoError(err)
}
func Test_EntAuthTokenRepo_GetUserByToken(t *testing.T) {
@ -65,8 +66,9 @@ func Test_EntAuthTokenRepo_GetUserByToken(t *testing.T) {
assert.Equal(userOut.Email, foundUser.Email)
// Cleanup
testRepos.Users.Delete(ctx, userOut.ID)
testRepos.AuthTokens.DeleteAll(ctx)
assert.NoError(testRepos.Users.Delete(ctx, userOut.ID))
_, err = testRepos.AuthTokens.DeleteAll(ctx)
assert.NoError(err)
}
func Test_EntAuthTokenRepo_PurgeExpiredTokens(t *testing.T) {
@ -108,6 +110,7 @@ func Test_EntAuthTokenRepo_PurgeExpiredTokens(t *testing.T) {
}
// Cleanup
testRepos.Users.Delete(ctx, userOut.ID)
testRepos.AuthTokens.DeleteAll(ctx)
assert.NoError(testRepos.Users.Delete(ctx, userOut.ID))
_, err = testRepos.AuthTokens.DeleteAll(ctx)
assert.NoError(err)
}

View file

@ -28,7 +28,8 @@ func Test_EntUserRepo_GetOneEmail(t *testing.T) {
user := UserFactory()
ctx := context.Background()
testRepos.Users.Create(ctx, user)
_, err := testRepos.Users.Create(ctx, user)
assert.NoError(err)
foundUser, err := testRepos.Users.GetOneEmail(ctx, user.Email)
@ -38,7 +39,8 @@ func Test_EntUserRepo_GetOneEmail(t *testing.T) {
assert.Equal(user.Name, foundUser.Name)
// Cleanup
testRepos.Users.DeleteAll(ctx)
err = testRepos.Users.DeleteAll(ctx)
assert.NoError(err)
}
func Test_EntUserRepo_GetOneId(t *testing.T) {
@ -55,7 +57,8 @@ func Test_EntUserRepo_GetOneId(t *testing.T) {
assert.Equal(user.Name, foundUser.Name)
// Cleanup
testRepos.Users.DeleteAll(ctx)
err = testRepos.Users.DeleteAll(ctx)
assert.NoError(err)
}
func Test_EntUserRepo_GetAll(t *testing.T) {
@ -95,11 +98,12 @@ func Test_EntUserRepo_GetAll(t *testing.T) {
}
for _, usr := range created {
testRepos.Users.Delete(ctx, usr.ID)
_ = testRepos.Users.Delete(ctx, usr.ID)
}
// Cleanup
testRepos.Users.DeleteAll(ctx)
err = testRepos.Users.DeleteAll(ctx)
assert.NoError(t, err)
}
func Test_EntUserRepo_Update(t *testing.T) {
@ -119,7 +123,8 @@ func Test_EntUserRepo_Delete(t *testing.T) {
allUsers, _ := testRepos.Users.GetAll(ctx)
assert.Greater(t, len(allUsers), 0)
testRepos.Users.DeleteAll(ctx)
err := testRepos.Users.DeleteAll(ctx)
assert.NoError(t, err)
allUsers, _ = testRepos.Users.GetAll(ctx)
assert.Equal(t, len(allUsers), 0)
@ -154,5 +159,6 @@ func Test_EntUserRepo_GetSuperusers(t *testing.T) {
}
// Cleanup
testRepos.Users.DeleteAll(ctx)
err = testRepos.Users.DeleteAll(ctx)
assert.NoError(t, err)
}

View file

@ -1,56 +0,0 @@
# Automapper
Automapper is an opinionated Go library that provides a dead simple interface to mapping 1-1 models To/From a database Model to a DTO or Schema using value semantics. It does not rely on code comments, but instead uses standard Go code to define your mapping and configuration to make it easy to use an refactor.
Current Limitation
- flat/single level models
- single schema to model per config entry
- limited configuration (support lowercase, camelcase, snakecase, etc)
Future Considerations
- [ ] Recursive mapping of embed structs
- [ ] Optional generate time type checker.
- [ ] Ensure values are copied to the destination and not just a reference
- [ ] ?!?!?
## Example Configuration
```go
package main
import (
"github.com/mealie-recipes/mealie-analytics/ent"
"github.com/mealie-recipes/mealie-analytics/internal/types"
"github.com/mealie-recipes/mealie-analytics/pkgs/automapper"
)
// getMappers serialized the config file into a list of automapper struct
func getMappers() []automapper.AutoMapper {
return []automapper.AutoMapper{
{
Package: "mapper", // generated package name
Prefix: "analytics", // generating file prefix -> analytics_automapper.go
Name: "Mealie Analytics", // For console output
Schema: automapper.Schema{
Type: types.Analytics{},
Prefix: "types", // Package namespace
},
Model: automapper.Model{
Type: ent.Analytics{},
Prefix: "ent", // Package namespace
},
Imports: []string{}, // Specify additional imports here
},
}
}
func main() {
automappers := getMappers()
conf := automapper.DefaultConf()
automapper.Generate(automappers, conf)
}
```

View file

@ -1,92 +0,0 @@
package automapper
import (
"bytes"
"fmt"
"go/format"
"os"
"reflect"
"strings"
"text/template"
)
type FieldAssignment struct {
ModelField string
SchemaField string
}
type Model struct {
Type interface{}
Prefix string
Fields []reflect.StructField
Reference string
}
type Schema struct {
Name string
Type interface{}
Prefix string
Fields []reflect.StructField
Reference string
}
type AutoMapper struct {
Name string
Package string
Prefix string
Schema Schema
Model Model
Imports []string
FieldAssignments []FieldAssignment
}
func (mapper *AutoMapper) ExecuteTemplates(conf *AutoMapperConf) {
t := template.New("automapper")
t, err := t.Parse(automapperTemplate)
if err != nil {
fmt.Println(err)
}
// Ensure the output directory exists
os.MkdirAll(conf.OutDir, 0755)
var path = fmt.Sprintf("%s/%s", conf.OutDir, mapper.GetFileName())
f, err := os.Create(path)
if err != nil {
panic(err)
}
defer f.Close()
var buf bytes.Buffer
err = t.Execute(&buf, mapper)
if err != nil {
fmt.Println(err)
}
text, err := format.Source(buf.Bytes())
if err != nil {
fmt.Println(err)
}
f.Write(text)
}
// GetFileName returns the computed file name based off user preference.
// If the Prefix has been specified on the AutoMapper it will be used
// in place of the Struct name. If the Prefix is not specified, the
// Struct name will be used.
//
// Examples:
// prefix_automapper.go
// mystructname_automapper.go
func (mapper *AutoMapper) GetFileName() string {
if mapper.Prefix == "" {
return strings.ToLower(mapper.Schema.Reference) + "_" + "automapper.go"
}
return strings.ToLower(mapper.Prefix) + "_" + "automapper.go"
}

View file

@ -1,11 +0,0 @@
package automapper
type AutoMapperConf struct {
OutDir string
}
func DefaultConf() *AutoMapperConf {
return &AutoMapperConf{
OutDir: "internal/mapper",
}
}

View file

@ -1,48 +0,0 @@
package automapper
import (
"fmt"
"reflect"
"strings"
)
func Generate(automappers []AutoMapper, conf *AutoMapperConf) {
for _, mapper := range automappers {
modelType := reflect.TypeOf(mapper.Model.Type)
transferObjectType := reflect.TypeOf(mapper.Schema.Type)
fmt.Printf("%s: %s -> %s\n", mapper.Name, modelType.Name(), transferObjectType.Name())
// From Fields
mapper.Imports = append(mapper.Imports, modelType.PkgPath())
mapper.Model.Reference = modelType.Name()
mapper.Model.Fields = make([]reflect.StructField, 0)
for i := 0; i < modelType.NumField(); i++ {
mapper.Model.Fields = append(mapper.Model.Fields, modelType.Field(i))
}
// To Fields
mapper.Imports = append(mapper.Imports, transferObjectType.PkgPath())
mapper.Schema.Reference = transferObjectType.Name()
mapper.Schema.Fields = make([]reflect.StructField, 0)
for i := 0; i < transferObjectType.NumField(); i++ {
mapper.Schema.Fields = append(mapper.Schema.Fields, transferObjectType.Field(i))
}
// Determine Field Assignments by matching the To fields and From fields by name
mapper.FieldAssignments = make([]FieldAssignment, 0)
for _, toField := range mapper.Schema.Fields {
for _, fromField := range mapper.Model.Fields {
if strings.EqualFold(toField.Name, fromField.Name) {
mapper.FieldAssignments = append(mapper.FieldAssignments, FieldAssignment{
ModelField: fromField.Name,
SchemaField: toField.Name,
})
}
}
}
mapper.ExecuteTemplates(conf)
}
}

View file

@ -1,22 +0,0 @@
package automapper
var automapperTemplate = `// Code generated by "/pkgs/automapper"; DO NOT EDIT.
package {{ .Package }}
import (
{{ range $import := .Imports }}"{{ $import }}"
{{ end }}
)
func {{ .Schema.Reference }}FromModel(from {{ .Model.Prefix}}.{{ .Model.Reference }}) {{ .Schema.Prefix}}.{{ .Schema.Reference }} {
return {{ .Schema.Prefix}}.{{ .Schema.Reference }}{ {{ range $i, $f := .FieldAssignments }}
{{ $f.SchemaField }}: from.{{ $f.ModelField }},{{ end }}
}
}
func {{ .Schema.Reference }}ToModel(from {{ .Schema.Prefix}}.{{ .Schema.Reference }}) {{ .Model.Prefix}}.{{ .Model.Reference }} {
return {{ .Model.Prefix}}.{{ .Model.Reference }}{ {{ range $i, $f := .FieldAssignments }}
{{ $f.ModelField }}: from.{{ $f.SchemaField }},{{ end }}
}
}
`

View file

@ -13,7 +13,7 @@ type Token struct {
func GenerateToken() Token {
randomBytes := make([]byte, 16)
rand.Read(randomBytes)
_, _ = rand.Read(randomBytes)
plainText := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(randomBytes)
hash := HashToken(plainText)

View file

@ -119,7 +119,7 @@ func (l *Logger) print(level Level, message string, properties map[string]string
n, err := l.out.Write(line)
if dumpTrace {
l.out.Write(debug.Stack())
n, err = l.out.Write(debug.Stack())
}
return n, err
}

View file

@ -8,6 +8,10 @@ import (
"github.com/stretchr/testify/assert"
)
func init() {
IncludeTrace = true
}
var lastWrite = []byte{}
type testLogRecorder struct {
@ -57,6 +61,7 @@ func getTestLogger(t *testing.T, level Level) *Logger {
}
func checkLastEntry(t *testing.T, level Level, message string, props *Props) {
t.Helper()
entry := &logEntry{}
entry.Unmarshal(t, lastWrite)

View file

@ -12,7 +12,8 @@ func testServer(t *testing.T, r http.Handler) *Server {
svr := NewServer("127.0.0.1", "19245")
go func() {
svr.Start(r)
err := svr.Start(r)
assert.NoError(t, err)
}()
ping := func() error {
@ -85,7 +86,7 @@ func Test_GracefulServerShutdownWithRequests(t *testing.T) {
// Make request to "/test"
go func() {
http.Get("http://127.0.0.1:19245/test") // This is probably bad?
_, _ = http.Get("http://127.0.0.1:19245/test") // This is probably bad?
}()
time.Sleep(time.Second) // Hack to wait for the request to be made