feat: add dynamic hospital database registry
This commit is contained in:
@@ -1,10 +1,22 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"primaya-api/cpone-middleware/internal/databaseconfig"
|
||||
"primaya-api/cpone-middleware/internal/repository"
|
||||
)
|
||||
|
||||
type selectedRepositoryKey struct{}
|
||||
|
||||
type DatabaseResolver interface {
|
||||
DefaultCode() string
|
||||
Resolve(ctx context.Context, code string) (repository.MySQLLayananRepository, error)
|
||||
}
|
||||
|
||||
func BearerAuth(staticToken string, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if bearerToken(r.Header.Get("Authorization")) != staticToken {
|
||||
@@ -20,6 +32,39 @@ func BearerAuth(staticToken string, next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
func SelectDatabase(resolver DatabaseResolver, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
code := strings.TrimSpace(r.Header.Get("X-RS-Code"))
|
||||
if code == "" {
|
||||
code = strings.TrimSpace(r.URL.Query().Get("kode_rs"))
|
||||
}
|
||||
if code == "" {
|
||||
code = resolver.DefaultCode()
|
||||
}
|
||||
code = databaseconfig.NormalizeRSCode(code)
|
||||
|
||||
repo, err := resolver.Resolve(r.Context(), code)
|
||||
if err != nil {
|
||||
if errors.Is(err, databaseconfig.ErrSettingNotFound) {
|
||||
WriteJSON(w, http.StatusNotFound, Response{Success: false,
|
||||
Message: "Setting database untuk kode RS " + code + " tidak ditemukan", Data: nil})
|
||||
return
|
||||
}
|
||||
WriteJSON(w, http.StatusServiceUnavailable, Response{Success: false,
|
||||
Message: "Database untuk kode RS " + code + " tidak dapat diakses", Data: nil})
|
||||
return
|
||||
}
|
||||
w.Header().Set("X-RS-Code", code)
|
||||
ctx := context.WithValue(r.Context(), selectedRepositoryKey{}, repo)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func selectedRepository(ctx context.Context) (repository.MySQLLayananRepository, bool) {
|
||||
repo, ok := ctx.Value(selectedRepositoryKey{}).(repository.MySQLLayananRepository)
|
||||
return repo, ok
|
||||
}
|
||||
|
||||
func bearerToken(header string) string {
|
||||
const prefix = "Bearer "
|
||||
if !strings.HasPrefix(header, prefix) {
|
||||
|
||||
Reference in New Issue
Block a user