package server import ( "context" "errors" "net/http" "git.1in9.net/raider/wroofauth/graph" "git.1in9.net/raider/wroofauth/internal/helpers/fetoken" chiprometheus "github.com/766b/chi-prometheus" "github.com/99designs/gqlgen/graphql" "github.com/99designs/gqlgen/graphql/handler" "github.com/99designs/gqlgen/graphql/playground" "github.com/go-chi/chi/v5" "github.com/go-chi/cors" ) func SetupAPI() chi.Router { router := chi.NewRouter() router.Use(cors.Handler(cors.Options{ AllowedOrigins: []string{"http://*", "https://*"}, AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"}, ExposedHeaders: []string{"Link"}, AllowCredentials: false, MaxAge: 300, })) m := chiprometheus.NewMiddleware("api") router.Use(m) router.Use(fetoken.Middleware()) router.NotFound(notFoundHandler) router.MethodNotAllowed(methodNotAllowedHandler) router.Handle("/", playground.Handler("GraphQL playground", "/api/query")) c := graph.Config{Resolvers: &graph.Resolver{}} c.Directives.FeToken = func(ctx context.Context, obj interface{}, next graphql.Resolver) (res interface{}, err error) { feToken := fetoken.ForContext(ctx) if feToken == nil { return nil, errors.New("FeToken is invalid") } return next(ctx) } c.Directives.Internal = func(ctx context.Context, obj interface{}, next graphql.Resolver) (res interface{}, err error) { // TODO return next(ctx) } c.Directives.Self = func(ctx context.Context, obj interface{}, next graphql.Resolver) (res interface{}, err error) { // TODO return next(ctx) } srv := handler.NewDefaultServer(graph.NewExecutableSchema(c)) router.Handle("/query", srv) return router } func notFoundHandler(res http.ResponseWriter, req *http.Request) { res.Header().Set("Content-Type", "application/json") res.WriteHeader(http.StatusNotFound) _, _ = res.Write([]byte(`{"error": "not found","error_code":404}`)) } func methodNotAllowedHandler(res http.ResponseWriter, req *http.Request) { res.Header().Set("Content-Type", "application/json") res.WriteHeader(http.StatusMethodNotAllowed) _, _ = res.Write([]byte(`{"error": "method not allowed","error_code":405}`)) }