Socialify

Folder ..

Viewing configHelper.ts
83 lines (75 loc) • 2.4 KB

 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
import { RepoQueryResponse } from './github/repoQuery'
import Configuration, {
  Font,
  OptionalConfigs,
  OptionalConfigsKeys,
  Pattern,
  Theme
} from './types/configType'
import QueryType from './types/queryType'

type Key = keyof typeof OptionalConfigsKeys

const DEFAULT_CONFIG: Configuration = {
  logo: '',
  font: Font.inter,
  theme: Theme.light,
  pattern: Pattern.plus
}

const getOptionalConfig = (repository: RepoQueryResponse['repository']) => {
  if (repository) {
    const languages = repository.languages?.nodes || []
    const language =
      languages.length > 0 ? languages[0]?.name || 'unknown' : 'unknown'
    const language2 =
      languages.length > 1 ? languages[1]?.name || 'unknown' : 'unknown'
    const newConfig: OptionalConfigs = {
      owner: { state: false, value: repository.owner.login },
      name: { state: true, value: repository.name },
      description: {
        state: false,
        editable: true,
        value: repository.description || ''
      },
      language: { state: false, value: language },
      language2: { state: false, value: language2 },
      stargazers: { state: false, value: repository.stargazerCount },
      forks: { state: false, value: repository.forkCount },
      pulls: { state: false, value: repository.pullRequests.totalCount },
      issues: { state: false, value: repository.issues.totalCount }
    }
    return newConfig
  }
  return null
}

const mergeConfig = (
  repository: RepoQueryResponse['repository'],
  query: QueryType
): Configuration | null => {
  if (!repository) {
    return null
  }

  const config: Configuration = {
    logo: query.logo || DEFAULT_CONFIG.logo,
    font: query.font || DEFAULT_CONFIG.font,
    pattern: query.pattern || DEFAULT_CONFIG.pattern,
    theme: query.theme || DEFAULT_CONFIG.theme
  }
  const optionalConfig = getOptionalConfig(repository)

  if (optionalConfig) {
    Object.assign(config, optionalConfig)
    for (const key in query) {
      if (key in OptionalConfigsKeys) {
        Object.assign(config[key as Key] ?? {}, {
          state: query[key as Key] === '1'
        })
        if (config[key as Key]?.editable) {
          const editableValue = query[`${key}Editable` as keyof typeof query]
          if (editableValue) {
            Object.assign(config[key as Key] ?? {}, { value: editableValue })
          }
        }
      }
    }
  }

  return config
}

export { DEFAULT_CONFIG, getOptionalConfig, mergeConfig }