summaryrefslogtreecommitdiff
path: root/cmd/start.go
blob: f6a2267299ea04f1d41db41ca4db1ba47c1a1fb9 (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
package cmd

import (
	"apjournal/config"
	"apjournal/internal/crons"
	"apjournal/internal/database/repos"
	database "apjournal/internal/database/sql"
	"apjournal/internal/server"
	"context"
	"os"

	"log/slog"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

func init() {
	rootCmd.AddCommand(startCmd)
}

var startCmd = &cobra.Command{
	Use:   "start",
	Short: "Start data server",
	Long:  `Start data server`,
	Run: func(cmd *cobra.Command, args []string) {
		log := slog.New(slog.NewJSONHandler(os.Stdout,
			&slog.HandlerOptions{Level: slog.LevelDebug, AddSource: true}))
		// load server configuration from server
		if viper.ConfigFileUsed() != "" {
			log.Debug("Configuration file loaded", "section", "init",
				"path", viper.ConfigFileUsed())
		}
		cfg := config.LoadConfig(viper.GetViper())
		db, err := database.Init(cfg.DBURI)
		if err != nil {
			log.Error("failed to connect to db", "error", err)
			return
		}
		repo := repos.NewProvider(db.Conn)
		srv := server.NewServer(cfg, log, repo)
		cron := crons.NewCron(context.Background(), repo)
		cron.StartCronJobs()
		// listen for new messages
		srv.Listen()
	},
}