Skip to content
This repository has been archived by the owner on Oct 25, 2022. It is now read-only.

Commit

Permalink
Better options
Browse files Browse the repository at this point in the history
  • Loading branch information
stefanoverna committed Oct 22, 2021
1 parent b1d55fe commit 7c179b2
Show file tree
Hide file tree
Showing 16 changed files with 118 additions and 75 deletions.
44 changes: 44 additions & 0 deletions src/Client.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,23 @@ export default class Client {
}

request(fetchRequest, preCallStack = new Error().stack, retryCount = 1) {
if (fetchRequest.options.logApiCalls) {
console.log('>>>>>>>>>>>>');
console.log(`${fetchRequest.options.method} ${fetchRequest.url}`);
if (fetchRequest.options.logApiCalls >= 2) {
for (const [key, value] of Object.entries(
fetchRequest.options.headers || {},
)) {
console.log(`${key}: ${value}`);
}
}
if (fetchRequest.options.logApiCalls >= 3 && fetchRequest.options.body) {
console.log();
console.log(fetchRequest.options.body);
}
console.log('>>>>>>>>>>>>');
}

return fetch(fetchRequest.url, fetchRequest.options)
.then(res => {
if (res.status === 429) {
Expand All @@ -104,8 +121,35 @@ export default class Client {
});
}

if (fetchRequest.options.logApiCalls) {
console.log('<<<<<<<<<<<<');
console.log(`Status: ${res.status}`);
if (fetchRequest.options.logApiCalls >= 2) {
[
'content-type',
'x-api-version',
'x-environment',
'x-queue-time',
'x-ratelimit-remaining',
].forEach(key => {
const value = res.headers.get(key);
if (value) {
console.log(`${key}: ${value}`);
}
});
}
}

return (res.status !== 204 ? res.json() : Promise.resolve(null))
.then(body => {
if (fetchRequest.options.logApiCalls >= 3 && body) {
console.log();
console.log(JSON.stringify(body));
}
if (fetchRequest.options.logApiCalls) {
console.log('<<<<<<<<<<<<');
console.log();
}
if (res.status >= 200 && res.status < 300) {
return Promise.resolve(body);
}
Expand Down
9 changes: 4 additions & 5 deletions src/contentfulImport/appClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,10 @@ export default async (
try {
const contentfulClient = createClient({ accessToken: contentfulToken });

const dato = new SiteClient(
datoCmsToken,
{ environment: datoCmsEnvironment },
datoCmsCmaBaseUrl,
);
const dato = new SiteClient(datoCmsToken, {
environment: datoCmsEnvironment,
baseUrl: datoCmsCmaBaseUrl,
});

const contentful = await contentfulClient.getSpace(contentfulSpaceId);
spinner.succeed();
Expand Down
10 changes: 5 additions & 5 deletions src/dump/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ export default async function(options) {
'X-SSG': detectSsg(process.cwd()),
};

if (environment) {
headers['X-Environment'] = environment;
}

const client = new SiteClient(token, headers, cmaBaseUrl);
const client = new SiteClient(token, {
environment,
headers,
baseUrl: cmaBaseUrl,
});

const loader = new Loader(client, previewMode, environment, { pageSize });

Expand Down
2 changes: 1 addition & 1 deletion src/environment/destroy/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default async function command({
`Destroying environment \`${environmentId}\`...\n`,
).start();
const token = tokenByArg || process.env.DATO_MANAGEMENT_API_TOKEN;
const client = new SiteClient(token, {}, cmaBaseUrl);
const client = new SiteClient(token, { baseUrl: cmaBaseUrl });

try {
await client.environments.destroy(environmentId);
Expand Down
2 changes: 1 addition & 1 deletion src/environment/getPrimary/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import SiteClient from '../../site/SiteClient';

export default async function command({ token: tokenByArg, cmaBaseUrl }) {
const token = tokenByArg || process.env.DATO_MANAGEMENT_API_TOKEN;
const client = new SiteClient(token, {}, cmaBaseUrl);
const client = new SiteClient(token, { baseUrl: cmaBaseUrl });

const allEnvs = await client.environments.all();
const primaryEnv = allEnvs.find(({ meta: { primary } }) => primary);
Expand Down
2 changes: 1 addition & 1 deletion src/environment/promote/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export default async function command({
).start();

const token = tokenByArg || process.env.DATO_MANAGEMENT_API_TOKEN;
const client = new SiteClient(token, {}, cmaBaseUrl);
const client = new SiteClient(token, { baseUrl: cmaBaseUrl });

try {
await client.environments.promote(environmentId);
Expand Down
2 changes: 1 addition & 1 deletion src/forkEnvironment/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default async function runPendingMigrations({
}) {
const token = tokenByArg || process.env.DATO_MANAGEMENT_API_TOKEN;

const client = new SiteClient(token, {}, cmaBaseUrl);
const client = new SiteClient(token, { baseUrl: cmaBaseUrl });
const allEnvironments = await client.environments.all();
const sourceEnv = await client.environments.find(sourceEnvId);

Expand Down
11 changes: 5 additions & 6 deletions src/runPendingMigrations/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export default async function runPendingMigrations({

const token = tokenByArg || process.env.DATO_MANAGEMENT_API_TOKEN;

const globalClient = new SiteClient(token, {}, cmaBaseUrl);
const globalClient = new SiteClient(token, { baseUrl: cmaBaseUrl });

const allEnvironments = await globalClient.environments.all();

Expand Down Expand Up @@ -83,11 +83,10 @@ export default async function runPendingMigrations({
forkSpinner.succeed();
}

const client = new SiteClient(
token,
{ environment: destinationEnvId },
cmaBaseUrl,
);
const client = new SiteClient(token, {
environment: destinationEnvId,
baseUrl: cmaBaseUrl,
});

const migrationModel = await upsertMigrationModel(
client,
Expand Down
2 changes: 1 addition & 1 deletion src/toggleMaintenanceMode/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default async function toggleMaintenanceMode({
cmaBaseUrl,
}) {
const token = tokenByArg || process.env.DATO_MANAGEMENT_API_TOKEN;
const client = new SiteClient(token, {}, cmaBaseUrl);
const client = new SiteClient(token, { baseUrl: cmaBaseUrl });

const { active } = await client.maintenanceMode.find();

Expand Down
40 changes: 29 additions & 11 deletions src/utils/generateClient.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import jsonref from 'json-schema-ref-parser';
import { singular } from 'pluralize';
import { decamelize, camelize } from 'humps';
import omit from 'object.omit';
import fetch from './fetch';
import deserializeJsonApi from './deserializeJsonApi';
import serializeJsonApi from './serializeJsonApi';
Expand Down Expand Up @@ -47,21 +48,34 @@ const findLinkFor = (schema, namespace, apiCall) => {
};

export default function generateClient(subdomain, cache, extraMethods = {}) {
return function Client(token, extraHeaders = {}, baseUrl) {
return function Client(
token,
rawLegacyHeadersArgOrOptions,
legacyBaseUrlArg,
) {
let schemaPromise;

const headers = { ...extraHeaders };
const legacyHeadersArgOrOptions = rawLegacyHeadersArgOrOptions || {};

if (extraHeaders && extraHeaders.environment) {
headers['X-Environment'] = extraHeaders.environment;
delete headers.environment;
const validOptions = ['environment', 'baseUrl', 'headers', 'logApiCalls'];

const headers = {
...omit(legacyHeadersArgOrOptions, validOptions),
...(legacyHeadersArgOrOptions.headers || {}),
};

if (legacyHeadersArgOrOptions.environment) {
headers['x-environment'] = legacyHeadersArgOrOptions.environment;
}

const rawClient = new RawClient(
token,
headers,
baseUrl || `https://${subdomain}.datocms.com`,
);
const globalOptions = legacyHeadersArgOrOptions;

const baseUrl =
legacyBaseUrlArg ||
legacyHeadersArgOrOptions.baseUrl ||
`https://${subdomain}.datocms.com`;

const rawClient = new RawClient(token, headers, baseUrl);

const extraProps = getProps(extraMethods);
const rawClientProps = getProps(rawClient);
Expand Down Expand Up @@ -129,7 +143,7 @@ export default function generateClient(subdomain, cache, extraMethods = {}) {
}

const queryString = args.shift() || {};
const options = args.shift() || {};
const options = { ...globalOptions, ...(args.shift() || {}) };

const deserializeResponse = Object.prototype.hasOwnProperty.call(
options,
Expand Down Expand Up @@ -225,6 +239,7 @@ export default function generateClient(subdomain, cache, extraMethods = {}) {
url,
body,
queryString,
options,
);

return rawClient
Expand All @@ -236,6 +251,7 @@ export default function generateClient(subdomain, cache, extraMethods = {}) {
url,
body,
queryString,
options,
);

return rawClient
Expand All @@ -246,6 +262,7 @@ export default function generateClient(subdomain, cache, extraMethods = {}) {
const fetchRequest = rawClient.buildDeleteRequest(
url,
queryString,
options,
);

return rawClient
Expand Down Expand Up @@ -274,6 +291,7 @@ export default function generateClient(subdomain, cache, extraMethods = {}) {
const fetchRequest = rawClient.buildGetRequest(
url,
queryString,
options,
);

return rawClient
Expand Down
2 changes: 1 addition & 1 deletion src/wpImport/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export default async function command(
cmaBaseUrl,
wpApiEndpointUrl,
) {
const dato = new SiteClient(token, { environment }, cmaBaseUrl);
const dato = new SiteClient(token, { environment, baseUrl: cmaBaseUrl });

let wp;

Expand Down
8 changes: 3 additions & 5 deletions test/src/SiteClientPro_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,9 @@ const shouldRunTest = () => {
const accountClient = await generateNewAccountClient();
site = await accountClient.sites.create({ name: 'Blog' });

client = new SiteClient(
site.readwriteToken,
null,
process.env.SITE_API_BASE_URL,
);
client = new SiteClient(site.readwriteToken, {
baseUrl: process.env.SITE_API_BASE_URL,
});
}),
);

Expand Down
8 changes: 3 additions & 5 deletions test/src/SiteClient_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,9 @@ describe('Site API', () => {
const accountClient = await generateNewAccountClient();
site = await accountClient.sites.create({ name: 'Blog' });

client = new SiteClient(
site.readwriteToken,
null,
process.env.SITE_API_BASE_URL,
);
client = new SiteClient(site.readwriteToken, {
baseUrl: process.env.SITE_API_BASE_URL,
});
}),
);

Expand Down
35 changes: 13 additions & 22 deletions test/src/cli_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,10 @@ describe('CLI tool', () => {
`migrate --destination=foobar --token=${site.readwriteToken} --cmaBaseUrl=${process.env.SITE_API_BASE_URL}`,
);

const client = new SiteClient(
site.readwriteToken,
{
environment: 'foobar',
},
process.env.SITE_API_BASE_URL,
);
const client = new SiteClient(site.readwriteToken, {
environment: 'foobar',
baseUrl: process.env.SITE_API_BASE_URL,
});

const model = await client.itemTypes.find('article');
expect(model.apiKey).to.eq('article');
Expand All @@ -118,11 +115,9 @@ describe('CLI tool', () => {
`maintenance on --token=${site.readwriteToken} --cmaBaseUrl=${process.env.SITE_API_BASE_URL}`,
);

const client = new SiteClient(
site.readwriteToken,
{},
process.env.SITE_API_BASE_URL,
);
const client = new SiteClient(site.readwriteToken, {
baseUrl: process.env.SITE_API_BASE_URL,
});

const { active } = await client.maintenanceMode.find();
expect(active).to.eq(true);
Expand All @@ -149,11 +144,9 @@ describe('CLI tool', () => {
name: 'Integration new test site',
});

const client = new SiteClient(
site.readwriteToken,
{},
process.env.SITE_API_BASE_URL,
);
const client = new SiteClient(site.readwriteToken, {
baseUrl: process.env.SITE_API_BASE_URL,
});

await client.environments.fork('main', {
id: 'my-sandbox-env',
Expand Down Expand Up @@ -184,11 +177,9 @@ describe('CLI tool', () => {
name: 'Integration new test site',
});

const client = new SiteClient(
site.readwriteToken,
{},
process.env.SITE_API_BASE_URL,
);
const client = new SiteClient(site.readwriteToken, {
baseUrl: process.env.SITE_API_BASE_URL,
});

const newSandboxName = 'my-sandbox-env';

Expand Down
8 changes: 3 additions & 5 deletions test/src/dump_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,9 @@ describe('dump', () => {
name: 'Integration new test site',
});

const client = new SiteClient(
site.readwriteToken,
{},
process.env.SITE_API_BASE_URL,
);
const client = new SiteClient(site.readwriteToken, {
baseUrl: process.env.SITE_API_BASE_URL,
});

const newSite = await client.site.find();
const faviconFilePath = path.resolve('test/fixtures/favicon.ico');
Expand Down
8 changes: 3 additions & 5 deletions test/src/uploadFile_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,9 @@ describe('Upload file from', async () => {
vcr('before', async () => {
const accountClient = await generateNewAccountClient();
site = await accountClient.sites.create({ name: 'Blog' });
client = new SiteClient(
site.readwriteToken,
null,
process.env.SITE_API_BASE_URL,
);
client = new SiteClient(site.readwriteToken, {
baseUrl: process.env.SITE_API_BASE_URL,
});
}),
);

Expand Down

0 comments on commit 7c179b2

Please sign in to comment.