Skip to content

Commit

Permalink
Booting instance with persisted urls
Browse files Browse the repository at this point in the history
refs TryGhost/Toolbox#116

- This is a PoC to check out how viable this approach is and if it's worth merging into main as a very quick win
- The `urls.json` is in a bad place right now should probably live in a data folder
  • Loading branch information
naz committed Nov 12, 2021
1 parent f5d46d0 commit 36bc054
Show file tree
Hide file tree
Showing 3 changed files with 643 additions and 3 deletions.
40 changes: 39 additions & 1 deletion core/server/services/url/UrlService.js
@@ -1,3 +1,4 @@
const fs = require('fs-extra');
const _debug = require('@tryghost/debug')._base;
const debug = _debug('ghost:services:url:service');
const _ = require('lodash');
Expand All @@ -23,6 +24,7 @@ class UrlService {
this.finished = false;
this.urlGenerators = [];

// Get urls
this.urls = new Urls();
this.queue = new Queue();
this.resources = new Resources(this.queue);
Expand Down Expand Up @@ -286,7 +288,16 @@ class UrlService {
async init() {
this.resources.initResourceConfig();
this.resources.initEvenListeners();
await this.resources.fetchResources();

const persistedUrls = await this.fetchUrls();
if (persistedUrls) {
this.urls = new Urls({
urls: persistedUrls
});
this.finished = true;
} else {
await this.resources.fetchResources();
}

// CASE: all resources are fetched, start the queue
this.queue.start({
Expand All @@ -296,6 +307,33 @@ class UrlService {
});
}

async persistUrls() {
return fs.writeFileSync('./urls.json', JSON.stringify(this.urls.urls, null, 4));
}

async fetchUrls() {
let urlsCacheExists = false;
let urls;

try {
await fs.stat('./urls.json');
urlsCacheExists = true;
} catch (e) {
urlsCacheExists = false;
}

if (urlsCacheExists) {
try {
const urlsFile = await fs.readFile('./urls.json', 'utf8');
urls = JSON.parse(urlsFile);
} catch (e) {
//noop as we'd start a long boot process if there are any errors in the file
}
}

return urls;
}

/**
* @description Reset this service.
* @param {Object} options
Expand Down
9 changes: 7 additions & 2 deletions core/server/services/url/Urls.js
Expand Up @@ -20,8 +20,13 @@ const events = require('../../lib/common/events');
* You can easily ask `this.urls[resourceId]`.
*/
class Urls {
constructor() {
this.urls = {};
/**
*
* @param {Object} [options]
* @param {Object} [options.urls] map of available URLs with their resources
*/
constructor({urls = {}} = {}) {
this.urls = urls;
}

/**
Expand Down

0 comments on commit 36bc054

Please sign in to comment.