mirror of
https://github.com/TryGhost/Ghost.git
synced 2025-02-03 23:00:14 -05:00
closes: https://github.com/TryGhost/Toolbox/issues/296 - This is a small change to permit any known API version to redirect to an unversioned URL - We include v2 because although it should have been deleted in 5.0 anyway, in the spirit of the change away from versioned URLs there's absolutely no sense in forcing people to update clients that still work for no reason. - We use a 307, because this preserves the original HTTP method, allowing POSTS, PUTs and DELETEs through as well as GETs - We set the accept-version header on the redirect, meaning that for example with a request to the old /v4/ api, Ghost will respond as though the client sent `accept-version: v4.0` and if there are known breaking changes, it may choose to inform the admin and owner users of these
40 lines
1.7 KiB
JavaScript
40 lines
1.7 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 versionMissmatchHandler = require('@tryghost/mw-api-version-mismatch');
|
|
const {APIVersionCompatibilityServiceInstance} = 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.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(versionMissmatchHandler(APIVersionCompatibilityServiceInstance));
|
|
apiApp.use(errorHandler.handleJSONResponse(sentry));
|
|
|
|
debug('Parent API setup end');
|
|
return apiApp;
|
|
};
|