Build a CRUD soccer games schedule app using web5.js

Build a CRUD soccer games schedule app using web5.js

In todays tutorial we are going to be building a CRUD app that users can use to create soccer game schedules ,read or see games that have been scheduled , update the scheduled games if there was any changes and delete the scheduled games.But first of all what is web5.js.

Web5.js is an sdk that makes it easier to build decentralised web5 applications on the web. Now we are done with introduction, lets start coding.

The tutorial have been broken into very simple steps , if followed we will get to our goal.

step 1: Create a directory

This will be the directory or folder where your app will be.

mkdir gametime-app
cd gametime-app

So we are going to call the app gametime. that's smart i know.

step 2: initialize a package.json file

npm init -y

step 3:install Web5

we need to install the web5.js sdk.

npm install @web5/api

Before we start coding there is one last thing we need to do.since the the default type is commonjs but we will be coding in module type we want to switch the type to module. we ca do that by adding "type":"module" to our package.json as seen in picture below.

step 4: create file

we want to create a file in root directory we can name it index.js.

touch index.js

For Windows using PowerShell:

New-Item index.js -ItemType File

step 5: import web5 sdk

Now, we want to start coding, so first, we import the Web5.js SDK into the project so we can use it.

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

that is good. but if using node.js 18 and earlier , you will need to add some more imports for it to work.

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

//Node 18 users: the following 3 lines are needed
import { webcrypto } from "node:crypto";
// @ts-ignore
if (!globalThis.crypto) globalThis.crypto = webcrypto;

now we are done with imports.

step 6 : Instantiate Web5 and Create DID

In Web5 apps, a user’s unique identifier - like an email address - is called a Decentralized Identifier (DID). so our users will need identifiers too.

const { web5, did: userDid } = await Web5.connect();

This Web5 instance is what you'll use to access the object did. Within the connect function we’re using ion as the DID method.you Learn more about ION and other DID methods.

step 7 :Create Interoperable Data

the apps must understand and support the same data structure. to achieve that we can use schema.org.

const schema = {
    context: "https://schema.org/",
    type: "SportsEvent",
    get uri() {
      return this.context + this.type;
    },
  };

Now, our data will be well structured.

step 8 :function to create soccer games schedule

We want to write a function that creates or adds the soccer game schedule. First, let's write some custom data. This JSON represents multiple soccer game schedules.

  // Soccer Match Schedule
let matches = [
    {
      "@context": schema.context,
      "@type": schema.type,
      name: "Soccer Match 1",
      startDate: "2023-11-30T18:00:00",
      location: {
        "@type": "Place",
        name: "Stadium 1",
        address: {
          "@type": "PostalAddress",
          streetAddress: "123 Main Street",
          addressLocality: "City 1",
          addressRegion: "State 1",
        },
      },
      competitor: [
        {
          "@type": "SportsTeam",
          name: "Home Team A",
        },
        {
          "@type": "SportsTeam",
          name: "Away Team B",
        },
      ],
    },
    {
      "@context": schema.context,
      "@type": schema.type,
      name: "Soccer Match 2",
      startDate: "2023-12-05T20:00:00",
      location: {
        "@type": "Place",
        name: "Stadium 2",
        address: {
          "@type": "PostalAddress",
          streetAddress: "456 Main Street",
          addressLocality: "City 2",
          addressRegion: "State 2",
        },
      },
      competitor: [
        {
          "@type": "SportsTeam",
          name: "Home Team C",
        },
        {
          "@type": "SportsTeam",
          name: "Away Team D",
        },
      ],
    },

  ];

Now the function that will add the data to the DWN. storage for web5.

//Create match schedule (write record to DWN)
async function addNewGameShedule(){
    for (const match of matches){
        const response = await web5.dwn.records.create({
            data: match,
            message: {
              schema: schema.uri,
              dataFormat: "application/json",
              published: true,
            },
          });

          if (response.status.code === 202) {
            console.log(`${match.competitor[0].name} plays ${match.competitor[1].name} at Home ${match.location.name} on ${match.startDate} `)
          }else {
            console.log(`${response.status}. Error adding match  to shedule for  ${match.name}`);
          }
    }
}

again we use a web5 method to added soccer games record to the DWN.

step 9: function to read or see soccer games

Now that we have data in the store, lets write a function that returns soccer game schedule stored on DWN.

  //Query for all the matches to be played. (search for DWN records)
  async function getMatches(){
    let {records} = await web5.dwn.records.query({
        message: {
            filter: {
              schema: schema.uri,
            },
          },
          dateSort: "createdAscending",
    });
    return records;
  }

step 10 : update soccer games time

the time for the soccer match may change and user may want to change or update the time for the game. so we need a function that can do that.

//Update match time 
async function updateMatchTime(match, newTime){
  let matchData = await match.data.json();
  console.log(`old match time for ${matchData.name}`, matchData.startDate);

  matchData.startDate = newTime
  let response = await match.update({
    data: matchData
});


if (response.status.code === 202) {
  //Obtain the updated record
  const { record: updatedMatchTime } = await web5.dwn.records.read({
    message: {
      filter: {
        recordId: match.id
      }
    }
  });

  const updatedData = await updatedMatchTime.data.json();
  console.log(`updated match time for ${matchData.name}`, updatedData.startDate);
} 
else console.log(`${response.status}. Error updating match time for ${matchData.name}`);
}

our function takes two parameter match(the particular soccer match you want to update its time) and newTime( new time of the match). it changes the old time and update the new time on DWN.

step 11: Delete all the games or matches scheduled

Maybe the scheduled games have been played and so the user will not have need for them so, we need a function that can delete all the scheduled games.

//Delete all games shedule
async function deletematches() {
  let matches = await getMatches();

  for (const match of matches) {
    let name = (await match.data.json()).name;
    let response = await web5.dwn.records.delete({
      message: {
        recordId: match.id,
      },
    });
    console.log(`deleted ${name}. status: ${response.status.code}`);
  }
}

Using the web5 method we are able to delete all matches scheduled.

step 12: call our functions

so final thing we want to do is to call our functions and exit process.

let existingMatchReview = await getMatches();
await addNewGameShedule();
await updateMatchTime(existingMatchReview[0],"2023-11-30T17:00:00");
await deletematches();
process.exit();

so our index.js should look like this

now lets run our code and see what we get. run the below script on the terminal.

node index.js

conclusion

From the article we have been able to build a CRUD app to shedule soccer games time using the web5 sdk. if you did not find this helpfull you can checkout this tutorial