Skip to content

Commit

Permalink
feat: storage actions + git module actions
Browse files Browse the repository at this point in the history
  • Loading branch information
NGPixel committed Apr 6, 2019
1 parent 16d88a7 commit 10df1b4
Show file tree
Hide file tree
Showing 10 changed files with 261 additions and 83 deletions.
57 changes: 51 additions & 6 deletions client/components/admin/admin-storage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,24 @@
.caption.mt-3 Currently set to every #[strong {{getDefaultSchedule(tgt.syncInterval)}}].
.caption The default is every #[strong {{getDefaultSchedule(tgt.syncIntervalDefault)}}].

template(v-if='tgt.actions && tgt.actions.length > 0')
v-divider.mt-3
v-subheader.pl-0 Actions
v-container.pt-0(grid-list-xl, fluid)
v-layout(row, wrap, fill-height)
v-flex(xs12, lg6, xl4, v-for='act of tgt.actions')
v-card.radius-7.grey(flat, :class='$vuetify.dark ? `darken-3-d5` : `lighten-3`', height='100%')
v-card-text
.subheading(v-html='act.label')
.body-1.mt-2(v-html='act.hint')
v-btn.mx-0.mt-3(
@click='executeAction(tgt.key, act.handler)'
outline
:color='$vuetify.dark ? `blue` : `primary`'
:disabled='runningAction'
:loading='runningActionHandler === act.handler'
) Run

</template>

<script>
Expand All @@ -170,6 +188,7 @@ import { LoopingRhombusesSpinner } from 'epic-spinners'
import statusQuery from 'gql/admin/storage/storage-query-status.gql'
import targetsQuery from 'gql/admin/storage/storage-query-targets.gql'
import targetExecuteActionMutation from 'gql/admin/storage/storage-mutation-executeaction.gql'
import targetsSaveMutation from 'gql/admin/storage/storage-mutation-save-targets.gql'
momentDurationFormatSetup(moment)
Expand All @@ -184,6 +203,8 @@ export default {
},
data() {
return {
runningAction: false,
runningActionHandler: '',
currentTab: 0,
targets: [],
status: []
Expand All @@ -209,12 +230,12 @@ export default {
mutation: targetsSaveMutation,
variables: {
targets: this.targets.map(tgt => _.pick(tgt, [
'isEnabled',
'key',
'config',
'mode',
'syncInterval'
])).map(str => ({...str, config: str.config.map(cfg => ({...cfg, value: JSON.stringify({ v: cfg.value.value })}))}))
'isEnabled',
'key',
'config',
'mode',
'syncInterval'
])).map(str => ({...str, config: str.config.map(cfg => ({...cfg, value: JSON.stringify({ v: cfg.value.value })}))}))
}
})
this.currentTab = 0
Expand All @@ -239,6 +260,30 @@ export default {
},
getDefaultSchedule(val) {
return moment.duration(val).format('y [years], M [months], d [days], h [hours], m [minutes]')
},
async executeAction(targetKey, handler) {
this.$store.commit(`loadingStart`, 'admin-storage-executeaction')
this.runningAction = true
this.runningActionHandler = handler
try {
await this.$apollo.mutate({
mutation: targetExecuteActionMutation,
variables: {
targetKey,
handler
}
})
this.$store.commit('showNotification', {
message: 'Action completed.',
style: 'success',
icon: 'check'
})
} catch (err) {
console.warn(err)
}
this.runningAction = false
this.runningActionHandler = ''
this.$store.commit(`loadingStop`, 'admin-storage-executeaction')
}
},
apollo: {
Expand Down
12 changes: 12 additions & 0 deletions client/graph/admin/storage/storage-mutation-executeaction.gql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
mutation($targetKey: String!, $handler: String!) {
storage {
executeAction(targetKey: $targetKey, handler: $handler) {
responseResult {
succeeded
errorCode
slug
message
}
}
}
}
5 changes: 5 additions & 0 deletions client/graph/admin/storage/storage-query-targets.gql
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ query {
key
value
}
actions {
handler
label
hint
}
}
}
}
10 changes: 10 additions & 0 deletions server/graph/resolvers/storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,16 @@ module.exports = {
} catch (err) {
return graphHelper.generateError(err)
}
},
async executeAction(obj, args, context) {
try {
await WIKI.models.storage.executeAction(args.targetKey, args.handler)
return {
responseResult: graphHelper.generateSuccess('Action completed.')
}
} catch (err) {
return graphHelper.generateError(err)
}
}
}
}
12 changes: 12 additions & 0 deletions server/graph/schemas/storage.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ type StorageMutation {
updateTargets(
targets: [StorageTargetInput]!
): DefaultResponse @auth(requires: ["manage:system"])

executeAction(
targetKey: String!
handler: String!
): DefaultResponse @auth(requires: ["manage:system"])
}

# -----------------------------------------------
Expand All @@ -51,6 +56,7 @@ type StorageTarget {
syncInterval: String
syncIntervalDefault: String
config: [KeyValuePair]
actions: [StorageTargetAction]
}

input StorageTargetInput {
Expand All @@ -68,3 +74,9 @@ type StorageStatus {
message: String!
lastAttempt: String!
}

type StorageTargetAction {
handler: String!
label: String!
hint: String!
}
20 changes: 20 additions & 0 deletions server/helpers/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,25 @@ module.exports = {
*/
generateHash(opts) {
return crypto.createHash('sha1').update(`${opts.locale}|${opts.path}|${opts.privateNS}`).digest('hex')
},
/**
* Inject Page Metadata
*/
injectPageMetadata(page) {
let meta = [
['title', page.title],
['description', page.description],
['published', page.isPublished.toString()],
['date', page.updatedAt],
['tags', '']
]
switch (page.contentType) {
case 'markdown':
return '---\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n---\n\n' + page.content
case 'html':
return '<!--\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n-->\n\n' + page.content
default:
return page.content
}
}
}
16 changes: 1 addition & 15 deletions server/models/pages.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,21 +130,7 @@ module.exports = class Page extends Model {
* Inject page metadata into contents
*/
injectMetadata () {
let meta = [
['title', this.title],
['description', this.description],
['published', this.isPublished.toString()],
['date', this.updatedAt],
['tags', '']
]
switch (this.contentType) {
case 'markdown':
return '---\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n---\n\n' + this.content
case 'html':
return '<!--\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n-->\n\n' + this.content
default:
return this.content
}
return pageHelper.injectPageMetadata(this)
}

/**
Expand Down
24 changes: 21 additions & 3 deletions server/models/storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ module.exports = class Storage extends Model {
newTargets.push({
key: target.key,
isEnabled: false,
mode: target.defaultMode || 'push',
mode: target.defaultMode || 'push',
syncInterval: target.schedule || 'P0D',
config: _.transform(target.props, (result, value, key) => {
_.set(result, key, value.default)
Expand Down Expand Up @@ -116,7 +116,7 @@ module.exports = class Storage extends Model {
}

// -> Initialize targets
for(let target of this.targets) {
for (let target of this.targets) {
const targetDef = _.find(WIKI.data.storage, ['key', target.key])
target.fn = require(`../modules/storage/${target.key}/storage`)
target.fn.config = target.config
Expand Down Expand Up @@ -161,12 +161,30 @@ module.exports = class Storage extends Model {

static async pageEvent({ event, page }) {
try {
for(let target of this.targets) {
for (let target of this.targets) {
await target.fn[event](page)
}
} catch (err) {
WIKI.logger.warn(err)
throw err
}
}

static async executeAction(targetKey, handler) {
try {
const target = _.find(this.targets, ['key', targetKey])
if (target) {
if (_.has(target.fn, handler)) {
await target.fn[handler]()
} else {
throw new Error('Invalid Handler for Storage Target')
}
} else {
throw new Error('Invalid or Inactive Storage Target')
}
} catch (err) {
WIKI.logger.warn(err)
throw err
}
}
}
8 changes: 7 additions & 1 deletion server/modules/storage/git/definition.yml
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,10 @@ props:
actions:
- handler: syncUntracked
label: Add Untracked Changes
hint: Output all content from the DB to the Git repo to ensure all untracked content is saved. If you enabled Git after content was created or you temporarily disabled Git, you'll want to execute this action to add the missing untracked changes.
hint: Output all content from the DB to the local Git repository to ensure all untracked content is saved. If you enabled Git after content was created or you temporarily disabled Git, you'll want to execute this action to add the missing untracked changes.
- handler: sync
label: Force Sync
hint: Will trigger an immediate sync operation, regardless of the current sync schedule. The sync direction is respected.
- handler: importAll
label: Import Everything
hint: Will import all content currently in the local Git repository, regardless of the latest commit state. Useful for importing content from the remote repository created before git was enabled.

0 comments on commit 10df1b4

Please sign in to comment.