Centralized base API path value across server codebase

refs https://github.com/TryGhost/Team/issues/1420

- This changeset makes the "/ghost/api" base path for the APIs centralized in one place and reused by dependent modules. There are couple benefits this refactor brings: easy way to spot where the API base path is used (was hard to find it in regexp) and makes it easy to change the hardcoded path to a configurable one in the future (e.g. host all APIs under `domain.tld/custom-path/awesome-apis/posts`)
- I hear that scream from the back of your head: "But hey! This introduced coupling to url-utils!". To that my unswer is: "No. This change only makes the coupling explicit, it's been there already and now can be addressed if we need to!".
- A neat thing about his change, making the API work on a custom path is one line away, by moving the hardcoded `/ghost/api` to a config ;)
This commit is contained in:
Naz 2022-03-09 17:15:12 +08:00
parent 6a25a0e0dd
commit 9c64d7af81
3 changed files with 8 additions and 3 deletions

View File

@ -1,5 +1,6 @@
const debug = require('@tryghost/debug')('web:backend');
const express = require('../../../shared/express');
const {BASE_API_PATH} = require('../../../shared/url-utils');
/**
*
@ -11,7 +12,7 @@ module.exports = () => {
// Wrap the admin and API apps into a single express app for use with vhost
const backendApp = express('backend');
backendApp.lazyUse('/ghost/api', require('../api'));
backendApp.lazyUse(BASE_API_PATH, require('../api'));
backendApp.lazyUse('/ghost/oauth', require('../oauth'));
backendApp.lazyUse('/ghost/.well-known', require('../well-known'));

View File

@ -27,7 +27,8 @@ const uncapitalise = (req, res, next) => {
let decodedURI;
const isSignupOrReset = pathToTest.match(/^(.*\/ghost\/(signup|reset)\/)/i);
const isAPI = pathToTest.match(/^(.*\/ghost\/api(\/(v[\d.]+|canary))?\/.*?\/)/i);
const isAPIRegExp = new RegExp(`^(.*${urlUtils.BASE_API_PATH}(/(v[\\d.]+|canary))?/.*?/)`, 'i');
const isAPI = pathToTest.match(isAPIRegExp);
if (isSignupOrReset) {
pathToTest = isSignupOrReset[1];

View File

@ -1,6 +1,8 @@
const UrlUtils = require('@tryghost/url-utils');
const config = require('./config');
const BASE_API_PATH = '/ghost/api';
const urlUtils = new UrlUtils({
getSubdir: config.getSubdir,
getSiteUrl: config.getSiteUrl,
@ -9,7 +11,8 @@ const urlUtils = new UrlUtils({
defaultApiVersion: config.get('api:versions:default'),
slugs: config.get('slugs').protected,
redirectCacheMaxAge: config.get('caching:301:maxAge'),
baseApiPath: '/ghost/api'
baseApiPath: BASE_API_PATH
});
module.exports = urlUtils;
module.exports.BASE_API_PATH = BASE_API_PATH;