Score:1

Using REST API services to create content with field entity references that do not yet exist

kr flag

I'm using Drupal 9.4 and trying to create content via the REST API web services where one of the field's in this content is a reference to a taxonomy term that doesn't exists until the current node is created.

My goal is to import content that looks like a multi paged forum thread with the 1st page being the "parent" of the group. This special field I call: "Parent Page" which is a entity reference. The way this works when done manually I first would create the content then edit it again and input the current node into this "Parent Page". This actually creates a taxonomy term which is how it links all the other sub-pages.

I currently have it working where I'm able to create all the pages in a loop. But missing the "parent page" field.

Score:1
kr flag

Using node.js, you'll need to make sure you have your code setup in async await to be able to create your first parent node and then edit it again after you create the term to itself. From there creating the other sub pages, you'll just be able to add in this entity reference easily.

Below is the code broken up into 3 functions:

postNode - To create nodes

postTerm - To create the taxonomy term

editParent - To "patch" update the parent node with the term

Be aware of the multiple async and and promise functions to account for the term creation that needs to happen after the first parent node is created.

const https = require('https');

async function fetchData() {
  try {
    const data = await postNode('Part 1 -- This is my title', 'body text here', '356', '1');
    const parsedData = JSON.parse(data);
    return parsedData; 
  } catch (error) {
    throw error;
  }
}

fetchData()
  .then(async (data) => {
    console.log(data);
    const myterm = await postTerm(data.title[0].value,'chats');
    const parsedMyterm = JSON.parse(myterm);

    const tidParent = parsedMyterm.tid[0].value;
    editParent(data.nid[0].value, tidParent);
    postNode('part 2', 'body text here', tidParent, '2');
    postNode('part 3', 'body text here', tidParent, '3');
    postNode('part 4', 'body text here', tidParent, '4');
  })
  .catch((error) => {
    console.error(error);
  });



function postNode (title, body, par, page) {
return new Promise((resolve, reject) => {
  const postData = JSON.stringify({
    type: [{ target_id: 'chats' }],
    title: [{ value: title }],
    body: [{ value: body, format: 'full_html' }],
    field_chat_parent: [{ target_id: par }],
    field_page: [{ value: page }],
  });

  const options = {
    hostname: 'mydomain.com',
    path: '/node?_format=json',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Basic ' + Buffer.from('myuser:password').toString('base64'),
      'Content-Length': Buffer.byteLength(postData),
    },
  };

  const request = https.request(options, (response) => {
    let data = '';

    response.on('data', (chunk) => {
      data += chunk;
    });

    response.on('end', () => {
      resolve(data);
    });
  });

  request.on('error', (error) => {
    reject(error);
  });

  request.write(postData);
  request.end();

});
}


function postTerm(termName, vocab) {
return new Promise((resolve, reject) => {
  const postData = JSON.stringify({
    vid: [{ target_id: vocab, target_type: 'taxonomy_vocabulary' }],
    name: [{ value: termName }],
  });

  const options = {
    hostname: 'mydomain.com',
    path: '/taxonomy/term?_format=json',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Basic ' + Buffer.from('myuser:password').toString('base64'),
      'Content-Length': Buffer.byteLength(postData),
    },
  };

  const request = https.request(options, (response) => {
    let data = '';

    response.on('data', (chunk) => {
      data += chunk;
    });

    response.on('end', () => {
      resolve(data);
    });
  });

  request.on('error', (error) => {
    reject(error);
  });

  request.write(postData);
  request.end();
});
}

function editParent (nid, par) {
  const postData = JSON.stringify({
    type: [{ target_id: 'chats' }],
    field_chat_parent: [{ target_id: par }]
  });

  const options = {
    hostname: 'xxxx.yyyy',
    path: '/node/'+nid+'?_format=json',
    method: 'PATCH',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Basic ' + Buffer.from('myuser:password').toString('base64'),
      'Content-Length': Buffer.byteLength(postData),
    },
  };

  const request = https.request(options, (response) => {
    let data = '';

    response.on('data', (chunk) => {
      data += chunk;
    });

    response.on('end', () => {
      console.log(data);
    });
  });

  request.on('error', (error) => {
    console.log(error);
  });

  request.write(postData);
  request.end();

}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.