0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-02-10 23:36:14 -05:00
ghost/core/server/web/api/app.js
Hannah Wolfe c6ae3c30d8 Moved content-version middleware onto api app
closes: https://github.com/TryGhost/Toolbox/issues/319

- at the moment, content-version is only set if one of our endpoints touches the request
  - this was demonstrated in the e2e tests, where many of the tests that set accept-version did not receive accept-version
- by moving the middleware out of the http module and onto the api app we ensure it's always done
- I put the code in the api-version-compatibility service to keep it all co-located
- ideally we will refactor that service slightly so it only exposes middleware
2022-05-02 19:05:14 +01:00

41 lines
1.6 KiB
JavaScript

const debug = require('@tryghost/debug')('web:api:default:app');
const config = require('../../../shared/config');
const express = require('../../../shared/express');
const sentry = require('../../../shared/sentry');
const errorHandler = require('@tryghost/mw-error-handler');
const APIVersionCompatibilityService = require('../../services/api-version-compatibility');
module.exports = function setupApiApp() {
debug('Parent API setup start');
const apiApp = express('api');
if (config.get('server:testmode')) {
apiApp.use(require('./testmode')());
}
// If there is a version in the URL, and this is a valid API URL containing admin/content
// Then 307 redirect (preserves the HTTP method) to a versionless URL with `accept-version` set.
apiApp.all('/:version(v2|v3|v4|canary)/:api(admin|content)/*', (req, res) => {
const {version} = req.params;
const versionlessURL = req.originalUrl.replace(`${version}/`, '');
if (version.startsWith('v')) {
res.header('accept-version', `${version}.0`);
} else {
res.header('accept-version', version);
}
res.redirect(307, versionlessURL);
});
apiApp.use(APIVersionCompatibilityService.contentVersion);
apiApp.lazyUse('/content/', require('./canary/content/app'));
apiApp.lazyUse('/admin/', require('./canary/admin/app'));
// Error handling for requests to non-existent API versions
apiApp.use(errorHandler.resourceNotFound);
apiApp.use(APIVersionCompatibilityService.errorHandler);
apiApp.use(errorHandler.handleJSONResponseV2(sentry));
debug('Parent API setup end');
return apiApp;
};