I am having troubles with adding a newly created mobiledoc segment to an existing post with a given ID. Authentication to the Admin API and the GET request (to pull out the updated_at field) work fine. Updating the title with the chained PUT request seems to work well, too.
However I am running into issues when I am trying to update the mobiledoc. I am using the html-to-mobiledoc tool https://github.com/TryGhost/Ghost-SDK/tree/master/packages/html-to-mobiledoc but I keep getting the error 422.
Can someone please tell me what I am doing wrong? I did spend a lot of time fiddling around with this issue.
This is my code:
const converter = require('@tryghost/html-to-mobiledoc');
// Create a token without the client
const jwt = require('jsonwebtoken');
const axios = require('axios');
// Admin API key goes here
const key = 'ADMIN-API_KEY';
// Split the key into ID and SECRET
const [id, secret] = key.split(':');
// Create the token (including decoding secret)
const token = jwt.sign({}, Buffer.from(secret, 'hex'), {
keyid: id,
algorithm: 'HS256',
expiresIn: '5m',
audience: `/v2/admin/`
});
// Make an authenticated request to create a post
const url = 'http://localhost:2368/ghost/api/v2/admin/posts/5db55dd518abc5390c725294';
const headers = { Authorization: `Ghost ${token}` };
//GET request
axios.get(url, { headers })
.then((response) => {
let updated=response.data.posts[0].updated_at;
console.log(updated);
let modoc=converter.toMobiledoc('<h1>Hello World!</h1>');
let modoc_str = JSON.stringify(modoc)
let payload = { posts: [{
title: "Fresh new title",
updated_at: updated,
mobile_doc: modoc_str
}]};
// PUT request
return axios.put(url, payload,{ headers })
})
.then(response => console.log(response.data))
.catch(error => console.error(error));