2021-07-13 17:14:25 +00:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"os"
|
|
|
|
"strconv"
|
|
|
|
|
|
|
|
"github.com/christianselig/apollo-backend/internal/api"
|
|
|
|
"github.com/christianselig/apollo-backend/internal/cmdutil"
|
|
|
|
"github.com/spf13/cobra"
|
2022-05-23 18:17:25 +00:00
|
|
|
"go.uber.org/zap"
|
2021-07-13 17:14:25 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func APICmd(ctx context.Context) *cobra.Command {
|
|
|
|
var port int
|
|
|
|
|
|
|
|
cmd := &cobra.Command{
|
|
|
|
Use: "api",
|
|
|
|
Args: cobra.ExactArgs(0),
|
|
|
|
Short: "Runs the RESTful API.",
|
|
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
2021-07-13 18:22:41 +00:00
|
|
|
port = 4000
|
2021-07-13 17:14:25 +00:00
|
|
|
if os.Getenv("PORT") != "" {
|
|
|
|
port, _ = strconv.Atoi(os.Getenv("PORT"))
|
|
|
|
}
|
|
|
|
|
2022-05-23 18:29:15 +00:00
|
|
|
logger := cmdutil.NewLogger("api")
|
2022-05-23 18:17:25 +00:00
|
|
|
defer func() { _ = logger.Sync() }()
|
2021-07-13 17:14:25 +00:00
|
|
|
|
|
|
|
statsd, err := cmdutil.NewStatsdClient()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer statsd.Close()
|
|
|
|
|
2022-06-27 14:36:01 +00:00
|
|
|
db, err := cmdutil.NewDatabasePool(ctx, 8)
|
2021-07-13 17:14:25 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer db.Close()
|
|
|
|
|
|
|
|
redis, err := cmdutil.NewRedisClient(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer redis.Close()
|
|
|
|
|
2022-03-12 17:50:05 +00:00
|
|
|
api := api.NewAPI(ctx, logger, statsd, redis, db)
|
2021-07-13 17:14:25 +00:00
|
|
|
srv := api.Server(port)
|
|
|
|
|
2021-09-25 13:19:42 +00:00
|
|
|
go func() { _ = srv.ListenAndServe() }()
|
2021-07-13 17:14:25 +00:00
|
|
|
|
2022-05-23 18:17:25 +00:00
|
|
|
logger.Info("started api", zap.Int("port", port))
|
2021-07-13 17:14:25 +00:00
|
|
|
|
|
|
|
<-ctx.Done()
|
|
|
|
|
2021-09-25 13:19:42 +00:00
|
|
|
_ = srv.Shutdown(ctx)
|
2021-07-13 17:14:25 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
return cmd
|
|
|
|
}
|