Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[admin-api] Add overridable makeRequest function #50

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/admin-api/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ module.exports = {
extends: [
'plugin:ghost/es',
]
};
}
128 changes: 78 additions & 50 deletions packages/admin-api/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,53 @@ import token from './token';

const supportedVersions = ['v2'];

export default function GhostAdminAPI({host, ghostPath = 'ghost', version, key}) {
export default function GhostAdminAPI(options) {
if (this instanceof GhostAdminAPI) {
return GhostAdminAPI({host, version, key});
return GhostAdminAPI(options);
}

if (!version) {
const defaultConfig = {
ghostPath: 'ghost',
makeRequest({url, method, data, params = {}, headers = {}}) {
return axios({
url,
method,
params,
data,
headers,
paramsSerializer(params) {
return Object.keys(params).reduce((parts, key) => {
const val = encodeURIComponent([].concat(params[key]).join(','));
return parts.concat(`${key}=${val}`);
}, []).join('&');
}
}).then((res) => {
return res.data;
});
}
};

const config = Object.assign({}, defaultConfig, options);

if (!config.version) {
throw new Error('GhostAdminAPI Config Missing: @tryghost/admin-api requires a "version" like "v2"');
}
if (!supportedVersions.includes(version)) {
if (!supportedVersions.includes(config.version)) {
throw new Error('GhostAdminAPI Config Invalid: @tryghost/admin-api does not support the supplied version');
}
if (!host) {
if (!config.host) {
throw new Error('GhostAdminAPI Config Missing: @tryghost/admin-api requires a "host" like "https://site.com"');
}
if (!/https?:\/\//.test(host)) {
if (!/https?:\/\//.test(config.host)) {
throw new Error('GhostAdminAPI Config Invalid: @tryghost/admin-api requires a "host" with a protocol like "https://site.com"');
}
if (host.endsWith('/')) {
if (config.host.endsWith('/')) {
throw new Error('GhostAdminAPI Config Invalid: @tryghost/admin-api requires a "host" without a trailing slash like "https://site.com"');
}
if (ghostPath.endsWith('/') || ghostPath.startsWith('/')) {
if (config.ghostPath.endsWith('/') || config.ghostPath.startsWith('/')) {
throw new Error('GhostAdminAPI Config Invalid: @tryghost/admin-api requires a "ghostPath" without a leading or trailing slash like "ghost"');
}
if (key && !/[0-9a-f]{24}:[0-9a-f]{64}/.test(key)) {
if (config.key && !/[0-9a-f]{24}:[0-9a-f]{64}/.test(config.key)) {
throw new Error('GhostAdminAPI Config Invalid: @tryghost/admin-api requires a "key" in following format {A}:{B}, where A is 24 hex characters and B is 64 hex characters');
}

Expand Down Expand Up @@ -165,54 +188,29 @@ export default function GhostAdminAPI({host, ghostPath = 'ghost', version, key})
return api;

function makeImageRequest(data) {
const endpoint = `/${ghostPath}/api/${version}/admin/images/`;
const url = `${host}${endpoint}`;

const headers = {
Authorization: `Ghost ${token(endpoint, key)}`,
'Content-Type': `multipart/form-data; boundary=${data._boundary}`
};

return axios({
url: url,
return makeApiRequest({
endpoint: endpointFor('images'),
method: 'POST',
data: data,
headers: headers
}).then((res) => {
return res.data;
data,
headers
});
}

function makeResourceRequest(resourceType, params, data = {}, method = 'GET') {
delete params.id;
let id;

if ((['GET', 'PUT', 'DELETE'].includes(method)) && (data.id || data.slug)) {
id = data.id || `slug/${data.slug}`;
}

const endpoint = `/${ghostPath}/api/${version}/admin/${resourceType}/${id ? (id + '/') : ''}`;
const url = `${host}${endpoint}`;

const headers = {
Authorization: `Ghost ${token(endpoint, key)}`
};

return axios({
url: url,
method: method,
params: params,
data: data,
paramsSerializer: (params) => {
return Object.keys(params).reduce((parts, key) => {
const val = encodeURIComponent([].concat(params[key]).join(','));
return parts.concat(`${key}=${val}`);
}, []).join('&');
},
headers
}).then((res) => {
return makeApiRequest({
endpoint: endpointFor(resourceType, data),
method,
params,
data
}).then((data) => {
if (method === 'DELETE') {
return res.data;
return data;
}

// HACK: the configuration/about endpoint doesn't match the typical
Expand All @@ -221,13 +219,43 @@ export default function GhostAdminAPI({host, ghostPath = 'ghost', version, key})
resourceType = 'configuration';
}

if (!Array.isArray(res.data[resourceType])) {
return res.data[resourceType];
if (!Array.isArray(data[resourceType])) {
return data[resourceType];
}
if (res.data[resourceType].length === 1 && !res.data.meta) {
return res.data[resourceType][0];
if (data[resourceType].length === 1 && !data.meta) {
return data[resourceType][0];
}
return Object.assign(res.data[resourceType], {meta: res.data.meta});
return Object.assign(data[resourceType], {meta: data.meta});
});
}

function endpointFor(resource, {id, slug} = {}) {
const {ghostPath, version} = config;
let endpoint = `/${ghostPath}/api/${version}/admin/${resource}/`;

if (id) {
endpoint = `${endpoint}${id}/`;
} else if (slug) {
endpoint = `${endpoint}slug/${slug}/`;
}

return endpoint;
}

function makeApiRequest({endpoint, method, data, params = {}, headers = {}}) {
const {host, key, makeRequest} = config;
const url = `${host}${endpoint}`;

headers = Object.assign({}, headers, {
Authorization: `Ghost ${token(endpoint, key)}`
});

return makeRequest({
url,
method,
data,
params,
headers
});
}
}
15 changes: 15 additions & 0 deletions packages/admin-api/test/admin-api.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -668,4 +668,19 @@ describe('GhostAdminAPI', function () {
});
});
});

it('allows makeRequest override', function () {
const makeRequest = () => {
return Promise.resolve({
configuration: {
test: true
}
});
};
const api = new GhostAdminAPI({host, version, key, makeRequest});

return api.configuration.read().then((data) => {
should.deepEqual(data, {test: true});
});
});
});