summaryrefslogtreecommitdiff
path: root/nexus/utils/urls/path.go
blob: ca44726f9af67bf4899f9f3b2bbeed10f0fc857a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package urls

import (
	"strings"

	"nexus/utils/collections"

	"github.com/gofiber/fiber/v2"
)

type HTTPMethod string

const (
	Delete  HTTPMethod = "DELETE"
	Get     HTTPMethod = "GET"
	Head    HTTPMethod = "HEAD"
	Options HTTPMethod = "OPTIONS"
	Patch   HTTPMethod = "PATCH"
	Post    HTTPMethod = "POST"
	Put     HTTPMethod = "PUT"
)

func Path(method HTTPMethod, path string, handler fiber.Handler, name string) {
	registry.Mutex.Lock()
	defer registry.Mutex.Unlock()

	namespace := registry.CurrentNamespace
	fullName := resolveFullName(namespace, name)
	fullPath := resolveFullPath(namespace, path)

	registry.Routes.Set(fullName, RegisteredRoute{
		Method:    method,
		Path:      path,
		Handler:   handler,
		Namespace: namespace,
		Name:      name,
		FullPath:  fullPath,
	})
}

func GetFullPath(routeName string) (string, bool) {
	registry.Mutex.Lock()
	defer registry.Mutex.Unlock()

	route, exists := registry.Routes.Get(routeName)
	if !exists {
		return "", false
	}

	return route.FullPath, true
}

func ResolvePath(routeName string, params collections.Record[string, string]) (string, bool) {
	registry.Mutex.Lock()
	defer registry.Mutex.Unlock()

	route, exists := registry.Routes.Get(routeName)
	if !exists {
		return "", false
	}

	resolved := route.FullPath
	for key, value := range params {
		resolved = strings.ReplaceAll(resolved, ":"+key, value)
	}

	return resolved, true
}

func resolveFullName(namespace string, name string) string {
	switch namespace {
	case "":
		return name
	default:
		return namespace + "." + name
	}
}

func resolveFullPath(namespace string, path string) string {
	switch namespace {
	case "":
		return ensureLeadingSlash(path)
	default:
		return "/" + namespace + ensureLeadingSlash(path)
	}
}

func bindPath(application *fiber.App, route RegisteredRoute) {
	switch route.Method {
	case Delete:
		application.Delete(route.FullPath, route.Handler)
	case Get:
		application.Get(route.FullPath, route.Handler)
	case Head:
		application.Head(route.FullPath, route.Handler)
	case Options:
		application.Options(route.FullPath, route.Handler)
	case Patch:
		application.Patch(route.FullPath, route.Handler)
	case Post:
		application.Post(route.FullPath, route.Handler)
	case Put:
		application.Put(route.FullPath, route.Handler)
	}
}

func ensureLeadingSlash(path string) string {
	switch strings.HasPrefix(path, "/") {
	case true:
		return path
	default:
		return "/" + path
	}
}