Create records on a DWN

Chris Siku - Oct 11 - - Dev Community

Once connected to the free DWN, this chapter will walk you through the process of creating records. You’ll learn the data structures involved, the syntax for record creation in JavaScript, and the best practices for ensuring data integrity.

By the end of this chapter, you will have the skills needed to generate and store data effectively on your Decentralized Web Node.

You can use the create function to obtain records and from a DWN.

A recap,

Up to now our index.js file look as on the image bellow
Connect to web5 and dwn

Before writing our first code, let's explore different ways of creating records on a DWN

  • Create a text record
const { record: textRecord } = await web5.dwn.records.create({
  data: "This is a text record",
  message: {
    dataFormat: "text/plain",
  },
});
Enter fullscreen mode Exit fullscreen mode
  • Create a json record
const { record: jsonRecord } = await web5.dwn.records.create({
  data: {
    content: 'This is the content',
    description: 'Here we have a Json recod!',
  },
  message: {
    dataFormat: 'application/json',
  },
});
Enter fullscreen mode Exit fullscreen mode

"Note: As we progress with creating images and files on the DWN, we will adjust our project settings and include one image and one file."

- add an image file and name it we5.png
- add a txt file and name it web5.txt
our work space should look as follow

Actual workspace

now create 2 variables in the index.js file to hold our image and text file

// index.js
//...

// Image file
const imageFile = new File(["test image content"], "web5.png", {
  type: "image/png",
});
const mockImage = {
  currentTarget: {
    files: [imageFile], // Simulate a file input
  },
};

// txt file
const txtFile = new File(["dummy content"], "web5.txt", {
  type: "text/plain",
});

const mockTxt = {
  currentTarget: {
    files: [txtFile], // Mimic the file input's files array
  },
};
Enter fullscreen mode Exit fullscreen mode
  • Create Image record
const createBlobRecord = async (event) => {
  const blob = new Blob(event.currentTarget.files, { type: "image/png" });
  const { status, record } = await web5.dwn.records.create({
    data: blob,
    message: {
      schema: "https://test.org/schema/image",
      dataFormat: "image/png",
    },
  });

  return record;
};

// Call the function and create the image on the DWN
createBlobRecord(mockImage).then((record) => {
  console.log(record);
});
Enter fullscreen mode Exit fullscreen mode
  • Create file record
const createFileRecord = async (event) => {
  const file = event.currentTarget.files[0];
  const { status: fileStatus, record: fileRecord } =
    await web5.dwn.records.create({
      data: file,
      message: {
        schema: "https://test.org/schema/file",
        dataFormat: "application/json",
      },
    });

  return fileRecord;
};

// Call the function and create the file on the DWN
createFileRecord(mockTxt).then((fileRecord) => {
  console.log(fileRecord);
});

Enter fullscreen mode Exit fullscreen mode
  • Create mixed record

Mixed record are record containing at the same time text, images, files, ...

const createMixedRecord = async (file, image, text) => {
  const { status, record } = await web5.dwn.records.create({
    data: {
      image,
      file,
      text,
    },
    message: {
      schema: "https://test.org/schema/mixed-data",
      dataFormat: "application/json",
    },
  });

  return record;
};

createMixedRecord(mockImage, mockTxt, "Mixed data");
Enter fullscreen mode Exit fullscreen mode
  • Create a record form an existing record

You can create a new version of a record while maintaining a link to the version of the original record.

const { record: newVersionRecord } = await web5.dwn.records.createFrom({
  record: originalRecord,
  data: 'I am a new version of the original record!',
  message: {
    dataFormat: 'text/plain',
    published: true,
  },
});
Enter fullscreen mode Exit fullscreen mode
  • Create a record with tags

You can assign tags to records to enable filtering by specific keywords

const { record } = await web5.dwn.records.create({
  data: 'Chocolate Chip Cookies',
  message: {
    dataFormat: 'application/json',
    tags: {
      dishType: 'Dessert',
      dietaryRestriction: 'Contains Gluten',
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

Note

  • when creating a record on a DWN you can choose to make it public or private. but it's private by default.
  • you can decide when to publish that record, directly or later. by default it's published directly

all you have to do is to add the following key into the message object when create a record

// .... 

const today = new Date();
const tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);

// Format the date and time in YYYY-MM-DDThh:mm:ss.ssssssZ format
const formattedDate = tomorrow.toISOString().replace(/\.\d{3}Z$/, '.000000Z');

{
// ....

message: {
    // .....
    published: true, // make public
    datePublished: formattedDate // publish at a specific moment
  },
}

Enter fullscreen mode Exit fullscreen mode

Implementation in our project

For our project will proceed with the mixed data to have everything in simple json form

update the index.js file and add the following code

// index.js
// ... 

// Image file
const imageFile = new File(["test image content"], "web5.png", {
  type: "image/png",
});
const mockImage = {
  currentTarget: {
    files: [imageFile], // Simulate a file input
  },
};

// txt file
const txtFile = new File(["dummy content"], "web5.txt", {
  type: "text/plain",
});

const mockTxt = {
  currentTarget: {
    files: [txtFile], // Mimic the file input's files array
  },
};

// Create Mixed record

const createMixedRecord = async (file, image, text) => {
  const { status, record } = await web5.dwn.records.create({
    data: {
      image,
      file,
      text,
    },
    message: {
      schema: "https://test.org/schema/mixed-data",
      dataFormat: "application/json",
    },
  });

  return record;
};

// run the function with data
createMixedRecord(mockImage, mockTxt, "Mixed data");

Enter fullscreen mode Exit fullscreen mode

and ... Voilà

at this point your index.js file should look as bellow

import { Web5 } from "@web5/api";

const { web5, did } = await Web5.connect({
  didCreateOptions: {
    dwnEndpoints: ["https://dwn.gcda.xyz"], // Community DWN instance on Google Cloud
  },
  registration: {
    onSuccess: () => {
      console.log("\n\nConnected successfully");
    },
    onFailure: (error) => {
      console.error("Connection failed:", error);
    },
  },
});

console.log("\nConnected did:", did);

// Image file
const imageFile = new File(["test image content"], "web5.png", {
  type: "image/png",
});
const mockImage = {
  currentTarget: {
    files: [imageFile], // Simulate a file input
  },
};

// txt file
const txtFile = new File(["dummy content"], "web5.txt", {
  type: "text/plain",
});

const mockTxt = {
  currentTarget: {
    files: [txtFile], // Mimic the file input's files array
  },
};

// Create Mixed record

const createMixedRecord = async (file, image, text) => {
  const { status, record } = await web5.dwn.records.create({
    data: {
      image,
      file,
      text,
    },
    message: {
      schema: "https://test.org/schema/mixed-data",
      dataFormat: "application/json",
    },
  });

  return record;
};

// run the function with data
createMixedRecord(mockImage, mockTxt, "Mixed data");
Enter fullscreen mode Exit fullscreen mode

Good job so far

Next ⏩️ ⏩️ ⏩️ Query and Read records on a DWN

Prev ⏪️ ⏪️ ⏪️ Connect to Web5 and on a DWN

. . . . . . .
Terabox Video Player