1

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.

1 Answer 1

1

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();

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.