Skip to content

Commit

Permalink
Add rename environment endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
stefanoverna committed Apr 11, 2024
1 parent 30e75b5 commit 2b18aef
Show file tree
Hide file tree
Showing 13 changed files with 156 additions and 57 deletions.
4 changes: 3 additions & 1 deletion generate/extractInfoFromSchema.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import JsonRefParser, { JSONSchema } from '@apidevtools/json-schema-ref-parser';
import JsonRefParser, {
type JSONSchema,
} from '@apidevtools/json-schema-ref-parser';
import fetch from 'cross-fetch';
import { compile as hyperschemaToTypings } from 'hyperschema-to-ts';
import simplifySchema from './generateSimplifiedSchema';
Expand Down
56 changes: 29 additions & 27 deletions generate/generateSimplifiedSchema.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import JsonRefParser from '@apidevtools/json-schema-ref-parser';

function simplifySchema(objectSchema: any) {
const { attributes, relationships, meta, id, type } =
objectSchema.properties as any;

return {
...objectSchema,
additionalProperties: attributes && !attributes.properties,
additionalProperties: Boolean(attributes && !attributes.properties),
required: [
...(objectSchema.required?.includes('attributes')
? attributes?.required || []
Expand All @@ -15,6 +13,9 @@ function simplifySchema(objectSchema: any) {
? relationships?.required || []
: []),
...(objectSchema.required?.includes('meta') ? ['meta'] : []),
...(!attributes && !relationships && !meta
? objectSchema.required.filter((attr: string) => attr !== 'type')
: []),
],
properties: {
...(id ? { id } : {}),
Expand Down Expand Up @@ -62,25 +63,23 @@ function simplifyEntity(objectSchema: any) {
...(id ? { id } : {}),
...(type ? { type } : {}),
...(attributes?.properties
? Object.keys(attributes.properties).reduce(
(acc, key) => ({
...acc,
[key]: {
? Object.fromEntries(
Object.keys(attributes.properties).map((key) => [
key,
{
$ref: `${objectSchema.properties.attributes.$ref}/properties/${key}`,
},
}),
{},
]),
)
: {}),
...(relationships?.properties
? Object.keys(relationships.properties).reduce(
(acc, key) => ({
...acc,
[key]: {
? Object.fromEntries(
Object.keys(relationships.properties).map((key) => [
key,
{
$ref: `${objectSchema.properties.relationships.$ref}/properties/${key}`,
},
}),
{},
]),
)
: {}),
...(meta ? { meta } : {}),
Expand All @@ -97,12 +96,12 @@ function simplifyEntityRelationships(schema: any) {
}

if (schema.definitions.relationships) {
Object.entries(schema.definitions.relationships.properties).forEach(
([rel, relSchema]) => {
schema.definitions.relationships.properties[rel] =
schema.definitions.relationships.properties[rel].properties.data;
},
);
for (const rel of Object.keys(
schema.definitions.relationships.properties,
)) {
schema.definitions.relationships.properties[rel] =
schema.definitions.relationships.properties[rel].properties.data;
}
}
}

Expand Down Expand Up @@ -150,10 +149,13 @@ function simplifyTargetSchema(schema: any) {
}

export default function simplifyLinks(schema: any) {
Object.entries<any>(schema.definitions).forEach(([jsonApiType, schema]) => {
simplifyEntityRelationships(schema);
if (schema.links) {
schema.links.forEach((link: any) => {
for (const [jsonApiType, subschema] of Object.entries<any>(
schema.definitions,
)) {
simplifyEntityRelationships(subschema);

if (subschema.links) {
for (const link of subschema.links) {
const originalSchema = link.schema;

link.schema = applyToInnerObject(
Expand All @@ -180,7 +182,7 @@ export default function simplifyLinks(schema: any) {
link.targetSchema?.properties?.data,
);
link.jobSchema = simplifyTargetSchema(link.jobSchema?.properties?.data);
});
}
}
});
}
}
10 changes: 5 additions & 5 deletions generate/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
#!/usr/bin/env node --stack_size=800 -r ts-node/register

import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import Handlebars from 'handlebars';
import rimraf from 'rimraf';
import extractInfoFromSchema, {
ResourceInfo,
SchemaInfo,
type ResourceInfo,
type SchemaInfo,
} from './extractInfoFromSchema';
import toSafeName from './toSafeName';

Expand Down Expand Up @@ -49,7 +49,7 @@ async function generate(prefix: string, hyperschemaUrl: string) {

writeFileSync(
`./packages/${prefix}-client/resources.json`,
JSON.stringify(
`${JSON.stringify(
other.resources.map((r) => ({
...r,
endpoints: r.endpoints.map(
Expand All @@ -61,7 +61,7 @@ async function generate(prefix: string, hyperschemaUrl: string) {
})),
null,
2,
) + '\n',
)}\n`,
{ encoding: 'utf-8' },
);

Expand Down
6 changes: 3 additions & 3 deletions generate/setClientVersion.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#!/usr/bin/env node -r ts-node/register

import { readFileSync, writeFileSync } from 'fs';
import { readFileSync, writeFileSync } from 'node:fs';

['cma-client', 'dashboard-client'].forEach((dir) => {
for (const dir of ['cma-client', 'dashboard-client']) {
const version: string = JSON.parse(
readFileSync(`./packages/${dir}/package.json`, 'utf8'),
).version;
Expand All @@ -16,4 +16,4 @@ import { readFileSync, writeFileSync } from 'fs';
sourceFile.replace(`@datocms/${dir}`, `@datocms/${dir} v${version}`),
'utf-8',
);
});
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"scripts": {
"prepare": "husky install",
"lint": "biome ci packages",
"format": "biome check packages --apply-unsafe && biome format --write packages",
"format": "biome check generate packages --apply-unsafe && biome format --write generate packages",
"test": "npm run lint && jest --maxConcurrency=5",
"test-next": "ACCOUNT_API_BASE_URL=http://account-api.lvh.me:3001 SITE_API_BASE_URL=http://site-api.lvh.me:3001 PUSHER_APP_KEY=12a5ddac68784be0fc59 PUSHER_CLUSTER=eu npm run test",
"generate": "./generate/index.ts && npm run format",
Expand Down
8 changes: 6 additions & 2 deletions packages/cma-client-node/__tests__/environment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,15 @@ describe('environments', () => {
},
);

await client.environments.promote(forkedEnvironment.id);
const renamedSandbox = await client.environments.rename(forkedEnvironment, {
id: 'renamed-sandbox',
});

await client.environments.promote(renamedSandbox);

await client.environments.promote(primaryEnvironment.id);

await client.environments.destroy(forkedEnvironment.id);
await client.environments.destroy(renamedSandbox);

const environments = await client.environments.list();
expect(environments.length).toEqual(1);
Expand Down
25 changes: 25 additions & 0 deletions packages/cma-client/resources.json
Original file line number Diff line number Diff line change
Expand Up @@ -2295,6 +2295,31 @@
"name": "promote",
"rawName": "rawPromote"
},
{
"returnsCollection": false,
"docUrl": "https://www.datocms.com/docs/content-management-api/resources/environment/rename",
"rel": "rename",
"urlTemplate": "/environments/${environmentId}/rename",
"method": "PUT",
"comment": "Rename an environment",
"urlPlaceholder": {
"variableName": "environmentId",
"isEntityId": true,
"relType": "EnvironmentData"
},
"requestBodyType": "EnvironmentRenameSchema",
"optionalRequestBody": false,
"requestStructure": {
"type": "environment",
"idRequired": true,
"attributes": [],
"relationships": []
},
"queryParamsRequired": false,
"responseType": "EnvironmentRenameTargetSchema",
"name": "rename",
"rawName": "rawRename"
},
{
"returnsCollection": true,
"docUrl": "https://www.datocms.com/docs/content-management-api/resources/environment/instances",
Expand Down
2 changes: 1 addition & 1 deletion packages/cma-client/src/generated/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ export class Client {
...this.config,
...options,
logFn: this.config.logFn || console.log,
userAgent: '@datocms/cma-client v3.1.8',
userAgent: '@datocms/cma-client',
baseUrl: this.baseUrl,
preCallStack: new Error().stack,
extraHeaders: {
Expand Down
22 changes: 22 additions & 0 deletions packages/cma-client/src/generated/SchemaTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8490,6 +8490,28 @@ export type EnvironmentPromoteTargetSchema = {
data: Environment;
};

/**
* This interface was referenced by `Environment`'s JSON-Schema
* via the `rename.schema` link.
*/
export type EnvironmentRenameSchema = {
data: {
type: EnvironmentType;
/**
* The new ID for the environment
*/
id: string;
};
};

/**
* This interface was referenced by `Environment`'s JSON-Schema
* via the `rename.targetSchema` link.
*/
export type EnvironmentRenameTargetSchema = {
data: Environment;
};

/**
* This interface was referenced by `Environment`'s JSON-Schema
* via the `instances.targetSchema` link.
Expand Down
25 changes: 14 additions & 11 deletions packages/cma-client/src/generated/SimpleSchemaTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1338,30 +1338,26 @@ export type EditingSessionUpdateSchema =
*/
type?: 'editing_session_enter_item';
item: ItemData;
[k: string]: unknown;
}
| {
/**
* JSON API type
*/
type?: 'editing_session_take_over_item';
item: ItemData;
[k: string]: unknown;
}
| {
/**
* JSON API type
*/
type?: 'editing_session_lock_item';
item: ItemData;
[k: string]: unknown;
}
| {
/**
* JSON API type
*/
type?: 'editing_session_unlock_item';
[k: string]: unknown;
};
/**
* This interface was referenced by `EditingSession`'s JSON-Schema
Expand Down Expand Up @@ -7359,7 +7355,6 @@ export type ItemBulkPublishSchema = {
type?: 'item_bulk_publish_operation';
items: ItemData[];
minItems?: unknown;
[k: string]: unknown;
};

/**
Expand All @@ -7370,7 +7365,6 @@ export type ItemBulkUnpublishSchema = {
type?: 'item_bulk_unpublish_operation';
items: ItemData[];
minItems?: unknown;
[k: string]: unknown;
};

/**
Expand All @@ -7381,7 +7375,6 @@ export type ItemBulkDestroySchema = {
type?: 'item_bulk_destroy_operation';
items: ItemData[];
minItems?: unknown;
[k: string]: unknown;
};

/**
Expand Down Expand Up @@ -8024,7 +8017,6 @@ export type UploadBulkTagSchema = {
export type UploadBulkDestroySchema = {
type?: 'upload_bulk_destroy_operation';
uploads: UploadData[];
[k: string]: unknown;
};

/**
Expand Down Expand Up @@ -8334,6 +8326,7 @@ export type Environment = {
};
export type EnvironmentForkJobSchema = Environment;
export type EnvironmentPromoteTargetSchema = Environment;
export type EnvironmentRenameTargetSchema = Environment;
export type EnvironmentSelfTargetSchema = Environment;
export type EnvironmentDestroyJobSchema = Environment;
/**
Expand Down Expand Up @@ -8392,9 +8385,20 @@ export type EnvironmentForkSchema = {
/**
* The ID of the forked environment
*/
id?: string;
id: string;
type?: EnvironmentType;
};

/**
* This interface was referenced by `Environment`'s JSON-Schema
* via the `rename.schema` link.
*/
export type EnvironmentRenameSchema = {
/**
* The new ID for the environment
*/
id: string;
type?: EnvironmentType;
[k: string]: unknown;
};

/**
Expand Down Expand Up @@ -9398,7 +9402,6 @@ export type SiteInvitationUpdateSchema = {
id?: SiteInvitationIdentity;
type?: SiteInvitationType;
role?: RoleData;
[k: string]: unknown;
};

/**
Expand Down
Loading

0 comments on commit 2b18aef

Please sign in to comment.