Routes

How to create a Route

A Route is basically a backend REST API, where you write code for some DB Operation or anything else. You make request to this route to get some data or execute any other logic on the server.

In order to create a route, fill the following details in the form : -

  1. Name - name of the route.

  2. Path – endpoint URL of the route.

  3. Active – Check / Uncheck if ready / not ready to used.

  4. Route Type: - MS – route type is microservice. SITE – for serving static content. API – for serving data from database. CORE – core route is for system specific operations.

  5. Method: - POST – to post some data. GET – to get some data.

  6. Script – Code goes here.

  7. Click on ‘create’ button. That’s it, you have created a Route.

MS / API Router :-

app.post('/submit', (req, res) => {

    const reqBody = req.body;
    const reqQueryParams = req.query;
    const reqParams = req.params;
    return res.json({message:"this is a sample route"});

});

MSV2 / API Router :-

app.post('/submit', (req, res) => {
    const reqBody = req.body;
    const reqQueryParams = req.query;
    const reqParams = req.params;
    return res.json({message:"this is a sample route"});
});

How to use API Routes In this guide, we'll walk through the process of creating an APIs like you do in your local nodejs setup without the need for deployment. Our example will use OB API exposed by the platform for you. For every native API of nodejs you will have to add ob. as a prefix. And thats it you can use native nodejs functions like you do here in your local setup.

Inserting Data with ob.db

const user = req.body;

const insert = {
  name:user.name,
  email:user.email,
  age:user.age,
};

ob.db.create("user", insert, {}, (err, document) => {
  if (err)
      ob.log({err});
  else
      res.json({message:"user successfully added"});
});

Here, we create a new user, save it to the database using the ob.db.create method provided by ob.db, and log the saved user to the console.

Querying Data with ob.db

const user = await ob.db.find("user", {email:"abc@xyz.com"})
    .project({
      _id: 1,
      email: 1,
      domain:1
    })
    .sort([["email", "asc"]])
    .toArray();

The ob.db.find method queries the database for users with the name 'John Doe', and the result is logged to the console.

Updating Data with ob.db

const query = {
  name:req.body.username,
}

const update = {
  $set: { age:23 },
}

const updateOptions = {
  propogate: false,
  sync: true,
  domain: "YOUR SPACE NAME",
  user: {
    userid: "obto.admin",
    user_name: "admin"
  }
};

const callBack =  (err, result) => {
  return res.json({message:"user updated successfully"})
}

ob.db.update("user", query, update, {}, updateOptions, callBack);

In this snippet, we use ob.db.update to update the email address of the user named 'John Doe' and log the result.

Deleting Data with ob.db

const recordToDelete = {
  email: req.body.email
};
ob.db.delete('pltf_post', recordToDelete, (err, result) => {
  if (err) {
    return res.sendStatus(400);
  }
  res.json({ status: 'ok'})
})

Here, we employ ob.db.delete to remove the user with the name 'John Doe' from the database, and a message is logged upon successful deletion.

Reading and Writing Files in Node.js In Node.js, working with files is a common task. Whether you need to read data from a file or save information to a file, Node.js provides built-in modules that make file I/O operations straightforward.

Reading Files with Node.js

Let's start by looking at how to read the contents of a file. Node.js provides the fs (File System) module for file-related operations. The following code snippet demonstrates how to read a file asynchronously using the fs.readFile function:

const fs = ob.fs;

// Specify the file path
const filePath = 'example.txt';

// Read file asynchronously
fs.readFile(filePath, 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading file:', err);
    return;
  }

  console.log('File content:', data);
});

In this code snippet:

  • fs: Import the fs module.

  • filePath: Specify the path to the file you want to read.

  • fs.readFile: Read the file asynchronously, providing the file path, encoding ('utf8' for text files), and a callback function to handle the result.

  • The callback function receives an error and the file content. If an error occurs, it's logged; otherwise, the content is printed to the console.

Writing Files with Node.js

Now, let's explore how to write data to a file. The fs.writeFile function allows you to write data to a file asynchronously. Here's a code snippet demonstrating file writing:

const fs = ob.fs;

// Specify the file path
const filePath = 'output.txt';

// Data to write to the file
const content = 'Hello, Node.js!';

// Write to file asynchronously
fs.writeFile(filePath, content, 'utf8', (err) => {
  if (err) {
    console.error('Error writing to file:', err);
    return;
  }

  console.log('File written successfully.');
});

Explanation of the code:

  • fs.writeFile: Write to the file asynchronously, providing the file path, data to be written, encoding, and a callback function to handle errors.

  • The callback function logs an error if one occurs; otherwise, it prints a success message.

These are basic examples of reading and writing files in Node.js. Depending on your use case, you may need to explore additional options and methods provided by the fs module.

Last updated