site.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. const graphHelper = require('../../helpers/graph')
  2. const _ = require('lodash')
  3. const CleanCSS = require('clean-css')
  4. const path = require('path')
  5. /* global WIKI */
  6. module.exports = {
  7. Query: {
  8. async sites () {
  9. const sites = await WIKI.models.sites.query()
  10. return sites.map(s => ({
  11. ...s.config,
  12. id: s.id,
  13. hostname: s.hostname,
  14. isEnabled: s.isEnabled
  15. }))
  16. },
  17. async siteById (obj, args) {
  18. const site = await WIKI.models.sites.query().findById(args.id)
  19. return site ? {
  20. ...site.config,
  21. id: site.id,
  22. hostname: site.hostname,
  23. isEnabled: site.isEnabled
  24. } : null
  25. },
  26. async siteByHostname (obj, args) {
  27. let site = await WIKI.models.sites.query().where({
  28. hostname: args.hostname
  29. }).first()
  30. if (!site && !args.exact) {
  31. site = await WIKI.models.sites.query().where({
  32. hostname: '*'
  33. }).first()
  34. }
  35. return site ? {
  36. ...site.config,
  37. id: site.id,
  38. hostname: site.hostname,
  39. isEnabled: site.isEnabled
  40. } : null
  41. }
  42. },
  43. Mutation: {
  44. /**
  45. * CREATE SITE
  46. */
  47. async createSite (obj, args) {
  48. try {
  49. // -> Validate inputs
  50. if (!args.hostname || args.hostname.length < 1 || !/^(\\*)|([a-z0-9\-.:]+)$/.test(args.hostname)) {
  51. throw WIKI.ERROR(new Error('Invalid Site Hostname'), 'SiteCreateInvalidHostname')
  52. }
  53. if (!args.title || args.title.length < 1 || !/^[^<>"]+$/.test(args.title)) {
  54. throw WIKI.ERROR(new Error('Invalid Site Title'), 'SiteCreateInvalidTitle')
  55. }
  56. // -> Check for duplicate catch-all
  57. if (args.hostname === '*') {
  58. const site = await WIKI.models.sites.query().where({
  59. hostname: args.hostname
  60. }).first()
  61. if (site) {
  62. throw WIKI.ERROR(new Error('A site with a catch-all hostname already exists! Cannot have 2 catch-all hostnames.'), 'SiteCreateDuplicateCatchAll')
  63. }
  64. }
  65. // -> Create site
  66. const newSite = await WIKI.models.sites.createSite(args.hostname, {
  67. title: args.title
  68. })
  69. return {
  70. status: graphHelper.generateSuccess('Site created successfully'),
  71. site: newSite
  72. }
  73. } catch (err) {
  74. return graphHelper.generateError(err)
  75. }
  76. },
  77. /**
  78. * UPDATE SITE
  79. */
  80. async updateSite (obj, args) {
  81. try {
  82. // -> Load site
  83. const site = await WIKI.models.sites.query().findById(args.id)
  84. if (!site) {
  85. throw WIKI.ERROR(new Error('Invalid Site ID'), 'SiteInvalidId')
  86. }
  87. // -> Check for bad input
  88. if (_.has(args.patch, 'hostname') && _.trim(args.patch.hostname).length < 1) {
  89. throw WIKI.ERROR(new Error('Hostname is invalid.'), 'SiteInvalidHostname')
  90. }
  91. // -> Check for duplicate catch-all
  92. if (args.patch.hostname === '*' && site.hostname !== '*') {
  93. const dupSite = await WIKI.models.sites.query().where({ hostname: '*' }).first()
  94. if (dupSite) {
  95. throw WIKI.ERROR(new Error(`Site ${dupSite.config.title} with a catch-all hostname already exists! Cannot have 2 catch-all hostnames.`), 'SiteUpdateDuplicateCatchAll')
  96. }
  97. }
  98. // -> Format Code
  99. if (args.patch?.theme?.injectCSS) {
  100. args.patch.theme.injectCSS = new CleanCSS({ inline: false }).minify(args.patch.theme.injectCSS).styles
  101. }
  102. // -> Update site
  103. await WIKI.models.sites.updateSite(args.id, {
  104. hostname: args.patch.hostname ?? site.hostname,
  105. isEnabled: args.patch.isEnabled ?? site.isEnabled,
  106. config: _.defaultsDeep(_.omit(args.patch, ['hostname', 'isEnabled']), site.config)
  107. })
  108. return {
  109. status: graphHelper.generateSuccess('Site updated successfully')
  110. }
  111. } catch (err) {
  112. WIKI.logger.warn(err)
  113. return graphHelper.generateError(err)
  114. }
  115. },
  116. /**
  117. * DELETE SITE
  118. */
  119. async deleteSite (obj, args) {
  120. try {
  121. // -> Ensure site isn't last one
  122. const sitesCount = await WIKI.models.sites.query().count('id').first()
  123. if (sitesCount?.count && _.toNumber(sitesCount?.count) <= 1) {
  124. throw WIKI.ERROR(new Error('Cannot delete the last site. At least 1 site must exists at all times.'), 'SiteDeleteLastSite')
  125. }
  126. // -> Delete site
  127. await WIKI.models.sites.deleteSite(args.id)
  128. return {
  129. status: graphHelper.generateSuccess('Site deleted successfully')
  130. }
  131. } catch (err) {
  132. WIKI.logger.warn(err)
  133. return graphHelper.generateError(err)
  134. }
  135. },
  136. /**
  137. * UPLOAD LOGO
  138. */
  139. async uploadSiteLogo (obj, args) {
  140. try {
  141. const { filename, mimetype, createReadStream } = await args.image
  142. WIKI.logger.info(`Processing site logo ${filename} of type ${mimetype}...`)
  143. if (!WIKI.extensions.ext.sharp.isInstalled) {
  144. throw new Error('This feature requires the Sharp extension but it is not installed.')
  145. }
  146. console.info(mimetype)
  147. const destFormat = mimetype.startsWith('image/svg') ? 'svg' : 'png'
  148. const destPath = path.resolve(
  149. process.cwd(),
  150. WIKI.config.dataPath,
  151. `assets/logo.${destFormat}`
  152. )
  153. await WIKI.extensions.ext.sharp.resize({
  154. format: destFormat,
  155. inputStream: createReadStream(),
  156. outputPath: destPath,
  157. width: 100
  158. })
  159. WIKI.logger.info('New site logo processed successfully.')
  160. return {
  161. status: graphHelper.generateSuccess('Site logo uploaded successfully')
  162. }
  163. } catch (err) {
  164. return graphHelper.generateError(err)
  165. }
  166. },
  167. /**
  168. * UPLOAD FAVICON
  169. */
  170. async uploadSiteFavicon (obj, args) {
  171. const { filename, mimetype, createReadStream } = await args.image
  172. console.info(filename, mimetype)
  173. return {
  174. status: graphHelper.generateSuccess('Site favicon uploaded successfully')
  175. }
  176. }
  177. }
  178. }