Best way to generate thousands of posts in Ghost

Hello,

I’m trying to create, using Admin API, thousands of posts in Ghost.

I simply want to count from 1 to 10000 and add the posts as:
Post number 1
Post number 2

Post number 10000

I set my API config:

const api = new GhostAdminAPI({
    url: 'http://localhost:2368',
    version: 'v2',
    key: 'my-admin-api-key-here'
});

I made the script and runs ok for 2,3 posts. But if I try to run 30 posts it throws some errors like this:

(node:456) UnhandledPromiseRejectionWarning: BookshelfRelationsError: An error o
ccurred
    at makeRequest.catch (D:\ghost-generate-posts\node_modules\@tryghost\admin-a
pi\lib\index.js:290:33)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:456) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This e
rror originated either by throwing inside of an async function without a catch b
lock, or by rejecting a promise which was not handled with .catch(). (rejection
id: 2)
(node:456) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprec
ated. In the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.

This script is pretty basic:

while (nrEnd >= nrStart) {
    api.posts.add({
        title: "Post number " + nrStart,
        mobiledoc: '{\"version\":\"0.3.1\",\"atoms\":[],\"cards\":[],\"markups\":[],\"sections\":[[1,\"p\",[[0,[],0,\"\"]]]]}',
        status: "published",
    });
   nrStart++;
}

What would be a better way to achieve my goal?

The problem is likely arising because you’re trying to immediately start 10,000 requests to the API.

api.posts.add() returns a promise so it’s async which means your loop will not block waiting for the .add() call to complete. You could re-arrange it to be sequential, maybe something like this:

let nrStart = 1;
let nrEnd = 10000;

async function addPosts() {
  while (nrEnd >= nrStart) {
    await api.posts.add({
        title: "Post number " + nrStart,
        mobiledoc: '{\"version\":\"0.3.1\",\"atoms\":[],\"cards\":[],\"markups\":[],\"sections\":[[1,\"p\",[[0,[],0,\"\"]]]]}',
        status: "published",
    });
    nrStart++;
  }
}

addPosts();

This will take a while, you could speed it up by adjusting the code to run a limited number of calls in parallel.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.