Npm package 'axios' in cloud code

Hey do anybody know how can we use any npm package in cloud functions. Basically I was trying some stuff with Pinata API, and it uses
var axios = require('axios');
everywhere.
So is there some way to import this package into cloud functions.

Yes, you can. If you watch your cloud file in a nodejs environment;

const axios = require('axios');

Moralis.Cloud.define("addNum", async (request) => {
  let id = request.params.postId 
  let res = await axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`)

  return res.data;
});
1 Like

Hey its great to hear, but can you just elaborate what is that you mean by watching cloud file in nodejs environment.

I mean creating a nodejs project setup ( a simple project with package.json ), installing the required package, require the package in your cloud file and watch the cloud folder afterwards

Ohh I get it, going to try it now! Thanks!

Well @qudusayo I tried it and it sucessfully failed even my cloud functions those were working earlier stopped working. BTW is this someway related to the fact that I’m using googleapis npm package too.

const { google } = require("googleapis");

const CLIENT_ID = "";
const CLIENT_SECRET = "";
const REDIRECT_URL = "";

const REFRESH_TOKEN = "";

const oauth2Client = new google.auth.OAuth2(
    CLIENT_ID,
    CLIENT_SECRET,
    REDIRECT_URL
);

const drive = google.drive({
    version: "v3",
    auth: oauth2Client,
});

oauth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });

Moralis.Cloud.define("storeImageOnDrive", async(request) => {
    const logger = Moralis.Cloud.getLogger();
    try {
       // try some stuff
    } catch (e) {
        logger.error(e);
    }
});

Here have a peek at my code.

Not sure what the issue is and maybe it doesn’t work in all cases, nonetheless you can try with the example with axios shared and see if it works for you.

Regards this, you need to update your cloud functions.

Yeah It worked perfectly fine in case of ‘axios’. Maybe the issue is with ‘googleapis’ being an external package.
I’m not sure about this.

googleapis isn’t installed by default unlike axios.

If you self host, you will be able to install libraries to use in cloud code.

Ohh so to install additional libraries I’ve to use self hosted server