Completed
Push — main ( c7f647...178139 )
by Yume
14s queued 13s
created

app/routes/app.go   A

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 45
dl 0
loc 73
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B routes.New 0 50 8
1
package routes
2
3
import (
4
	"github.com/bytedance/sonic"
5
	"github.com/gofiber/fiber/v2"
6
	"github.com/gofiber/fiber/v2/middleware/cache"
7
	"github.com/gofiber/fiber/v2/middleware/compress"
8
	"github.com/gofiber/fiber/v2/middleware/cors"
9
	"github.com/gofiber/swagger"
10
	_ "github.com/memnix/memnixrest/docs" // Side effect import
11
	"github.com/memnix/memnixrest/pkg/models"
12
13
	"time"
14
)
15
16
type routeStruct struct {
17
	Method     string
18
	Handler    func(c *fiber.Ctx) error
19
	Permission models.Permission
20
}
21
22
var routesMap map[string]routeStruct
23
24
func New() *fiber.App {
25
	// Create new app
26
	app := fiber.New(
27
		fiber.Config{
28
			JSONEncoder: sonic.Marshal,
29
			JSONDecoder: sonic.Unmarshal,
30
		})
31
32
	app.Use(cors.New(cors.Config{
33
		AllowOrigins:     "http://localhost, *",
34
		AllowHeaders:     "Origin, Content-Type, Accept, Authorization",
35
		AllowCredentials: true,
36
	}))
37
38
	app.Use(compress.New(compress.Config{
39
		Level: compress.LevelBestSpeed, // 2
40
	}))
41
42
	app.Use(cache.New(cache.Config{
43
		Next: func(c *fiber.Ctx) bool {
44
			return c.Query("refresh") == "true" || c.Path() == "/v1/user" || c.Path() == "/v1/login" || c.Path() == "/v1/register" || c.Path() == "/v1/logout"
45
		},
46
		Expiration:   2 * time.Minute,
47
		CacheControl: true,
48
	}))
49
50
	app.Get("/swagger/*", swagger.HandlerDefault) // default
51
52
	// Api group
53
	v1 := app.Group("/v1")
54
55
	v1.Get("/", func(c *fiber.Ctx) error {
56
		return fiber.NewError(fiber.StatusForbidden, "This is not a valid route") // Custom error
57
	})
58
59
	v1.Use(IsConnectedMiddleware())
60
61
	// Register routes
62
	routesMap = make(map[string]routeStruct)
63
64
	registerAuthRoutes() // /v1/
65
	registerUserRoutes() // /v1/users/
66
	registerDeckRoutes() // /v1/decks/
67
	registerCardRoutes() // /v1/cards/
68
69
	for route, routeData := range routesMap {
70
		v1.Add(routeData.Method, route, routeData.Handler)
71
	}
72
73
	return app
74
}
75