Skip to content

Instantly share code, notes, and snippets.

@ChazUK
Last active February 21, 2023 11:34
Show Gist options
  • Save ChazUK/52c3eb64908d13ecd728de4808e7a358 to your computer and use it in GitHub Desktop.
Save ChazUK/52c3eb64908d13ecd728de4808e7a358 to your computer and use it in GitHub Desktop.
Contentful Management API running through ts-node
CONTENTFUL_SPACE_ID="..."
CONTENTFUL_ENVIRONMENT="..."
CONTENTFUL_DELIVERY_API_KEY="..."
CONTENTFUL_PREVIEW_API_KEY="..."
CONTENTFUL_MANAGEMENT_ACCESS_TOKEN="..."
import contentful from "contentful-management";
import * as dotenv from "dotenv";
import { exportedTags, type ExportedTag } from "./tags";
dotenv.config();
const client = contentful.createClient({
accessToken: process.env.CONTENTFUL_MANAGEMENT_ACCESS_TOKEN!,
});
const space = await client.getSpace(process.env.CONTENTFUL_SPACE_ID!);
const environment = await space.getEnvironment(
process.env.CONTENTFUL_ENVIRONMENT!
);
console.log(space, environment);
const deleteTags = async () => {
const tags = await environment.getTags();
tags.items.forEach(async (tag) => {
await tag.delete();
console.log("Deleted", tag.name);
});
};
const createTags = async () => {
exportedTags.forEach(async (tag: ExportedTag) => {
const t = await environment.createTag(tag.tagSlug, tag.tagTitle);
console.log("Created", t.name, t.sys.id);
});
};
{
"name": "contentful-importer",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"import": "ts-node --esm ./ContentfulManagement.ts"
},
"dependencies": {
"@contentful/rich-text-react-renderer": "^15.16.2"
},
"devDependencies": {
"@contentful/rich-text-from-markdown": "^15.16.3",
"@types/node": "18.11.18",
"contentful-management": "^10.29.3",
"dotenv": "^16.0.3",
"prettier": "2.8.3",
"ts-node": "^10.9.1",
"typescript": "4.9.4"
}
}
export type ExportedTag = {
tagID: number;
tagTitle: string;
tagSlug: string;
};
export const exportedTags: ExportedTag[] = [
{
tagID: 1,
tagTitle: "Organic",
tagSlug: "organic",
},
{
tagID: 2,
tagTitle: "International",
tagSlug: "international",
},
];
{
"compilerOptions": {
"target": "esnext",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
}
},
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"],
"ts-node": {
// these options are overrides used only by ts-node
"compilerOptions": {
"target": "esnext",
"module": "esnext"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment