appwrite/sdk-for-node

Bug: function that database

cambo2015 opened this issue · 16 comments

I tried to create a collection inside of a function but instead, of it creating a collection I get this error.

TypeError: Cannot read property 'statusText' of undefined
at Client.call (/usr/local/src/node_modules/node-appwrite/lib/client.js:163:64)
at processTicksAndRejections (node:internal/process/task_queues:93:5)
at async Database.createCollection (/usr/local/src/node_modules/node-appwrite/lib/services/database.js:94:16)

@lohanidamodar my guess is that this is a problem parsing a non-json error message.

@cambo2015 are you sure your'e using the correct endpoint hostname to allow you to connect with Appwrite?
What does your code look like?

For accessing your Appwrite instance from within the function runtime you could use: http://host.docker.internal/v1 as the Appwrite endpoint.

@lohanidamodar my guess is that this is a problem parsing a non-json error message.

@cambo2015 are you sure your'e using the correct endpoint hostname to allow you to connect with Appwrite?
What does your code look like?

Yes the error is because of that, but not sure of a condition to reproduce it. Code would be helpful in reproducing and fixing

@cambo2015 can you share the code you are trying to execute

@TorstenDittmann would also appreciate your help when you are available.

Thanks, everyone. Give me a minute and I will share it.

database
    .createCollection(
      "user-info",
      ["*"],
      ["*"],
      [
        {
          key: "User Id",
          label: "User Id",
          type: "text",
          default: "",
          required: true,
          array: false,
        },
        {
          key: "stripeId",
          label: "Stripe Id",
          type: "text",
          default: "",
          required: true,
          array: false,
        },
        {
          key: "paid",
          label: "Paid",
          type: "boolean",
          default: false,
          required: true,
          array: false,
        },
      ]
    )
    .then((x) => {
      if (!x) {
        console.log("db collection not created")
        return
      }
      console.log(`x exists ${x}`)
      return
    })
    .catch((error) => {
      console.log(error)
      return
    })

@eldadfux yes I am sure. It was executing but still gave me that error. I ended up deleting that server and started a new instance via digital ocean. After that, the error went away when I added selfsigned() after the setKey() and when nodejs 15.5 on my local machine matched the appwrite function.

here is the order I executed it. I remove my keys

client
  .setEndpoint()
  .setProject()
  .setKey()
  .setSelfSigned()

here is the entire code . I took my keys out for obvious reasons. The code would execute when a new account was created. I suspect APPWRITE_FUNCTION_EVENT_DATA might have something to do with it. I will see if I get this error today. Thank you all.

const sdk = require("node-appwrite")
const data = JSON.parse(process.env.APPWRITE_FUNCTION_EVENT_DATA)
const { name, email } = data
const logger = []

const client = new sdk.Client()
client
  .setEndpoint()
  .setProject()
  .setKey(
   
  ).setSelfSigned()

const database = new sdk.Database(client)

const main =  () => {
  return  database
    .createCollection(
      "user-info",
      ["*"],
      ["*"],
      [
        {
          key: "User Id",
          label: "User Id",
          type: "text",
          default: "",
          required: true,
          array: false,
        },
        {
          key: "stripeId",
          label: "Stripe Id",
          type: "text",
          default: "",
          required: true,
          array: false,
        },
        {
          key: "paid",
          label: "Paid",
          type: "boolean",
          default: false,
          required: true,
          array: false,
        },
      ]
    )
    .then((x) => {
      if (!x) {
        console.log("db collection not created")
        return
      }
      console.log(`x exists ${x}`)
      return
    })
    .catch((error) => {
      console.log(error)
      return
    })
}

main()

Yes, I still encounter errors. I just tried to add process.env.APPWRITE_FUNCTION_EVENT_DATA to my file but it produced undesired behavior. It worked until this. Here is the result ->

  • I added process.env.APPWRITE_FUNCTION_EVENT_DATA to my file.
  • The function results said that the name and the email attributes were undefined.
  • Then I created a new user and didn't get anything.
  • The function did not finish running.
    I will check docker doctor and see if anything is down.

here is the code for this new function I made. Again I left keys out.

const sdk = require("node-appwrite")

const data = JSON.parse(process.env.APPWRITE_FUNCTION_EVENT_DATA)

const {name,email} = data
//variables
const colName = "user-info"



const client = new sdk.Client()
client
  .setEndpoint()
  .setProject()
  .setKey()

const database = new sdk.Database(client)



/**
 * @description inserts a doc into a collection via colId
 * @param {String} colId 
 */
const createDoc = async (colId) => {
    await database.createDocument(colId, {
        userId: data['$id'],
        
    }, ["*"], ["*"]).then(x => {
        if (x !== null || x !== undefined) console.log(' document is undefined')
        console.log(`success! Document created`)
    }).catch(error=>console.error(error))
}


/**
 * @description creates collection and inserts doc into collection
 */
const createBoth = async () => {
    await database.createCollection(
        colName,
        ["*"],
        ["*"],
        [
          {
            type: "text",
            key: "name",
            label: "name",
            required: true,
            array: false,
          },
        ]
    ).then((db)=> {
        const id = db['$id']
        createDoc(id)
    } ).catch(error=>console.error(error))
}


database
  .listCollections()
  .then((db) => {
    if (Array.isArray(db.collections)) {
      const temp = db.collections.filter((obj) => obj.name === colName) //will return an empty arr if nothing found
  

      if (temp.length > 0) {
        //exists //insert into array
          const id = temp[0]['$id']
          createDoc(id)
         
      } else {
        //does not exist so create both 
        createBoth()
      }
    } else {
      // console.log(typeof db)
      console.error("code 500. db.collections not an array")
    }
  })

  .catch((error) => console.error(error))

I also tried just the event env variable by itself and it works without errors: EDIT: Looks like this function won't even finish running now.

const sdk = require("node-appwrite")
const data = JSON.parse(process.env.APPWRITE_FUNCTION_EVENT_DATA)

const client = new sdk.Client()
client
  .setEndpoint()
  .setProject()
  .setKey()
  .setSelfSigned()

console.log(data["$id"])

@eldadfux Hopefully, this is enough info. Let me know if you need more

i got this bug too, after functions execution
here is my code

const sdk = require("node-appwrite");
const client = new sdk.Client();
const database = new sdk.Database(client);

client
  .setEndpoint(process.env.APPWRITE_ENDPOINT) // Your API Endpoint
  .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID) // Your project ID available by default
  .setKey(process.env.APPWRITE_API_KEY);

const collectionId = "60d007cfbc786";
const promise = database.listDocuments(collectionId);

promise
  .then((res) => console.log("response", res))
  .catch((err) => console.error("error", err));

and here stderr from executions

{
	"message": "connect ECONNREFUSED 127.0.0.1:3003",
	"name": "Error",
	"stack": "Error: connect ECONNREFUSED 127.0.0.1:3003\n    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1138:16)",
	"config": {
		"url": "http://localhost:3003/v1/database/collections/60d007cfbc786/documents",
		"method": "get",
		"data": null,
		"headers": {
			"Accept": "application/json, text/plain, */*",
			"x-sdk-version": "appwrite:nodejs:2.3.0",
			"X-Appwrite-Response-Format": "0.8.0",
			"x-appwrite-project": "60d006366ca8c",
			"x-appwrite-key": "a1a659f52694a6a1a2477e9016e1d9111b34639c0f5bc635ceb548b40bb9e8a87d29cefbe8497dd982da72dc7f82ea92bb79ea4224c0bbc436ad8058fdea13e7a85a765d1db1552fdfdff582e45943299806dcd6042a62d9513775a836ed8dba817a5a7ccc7c28d4a0f3e9654c1a857c0031b5bf147b5a1ae0cb5bec8b70a15e",
			"Content-Type": "application/json",
			"User-Agent": "axios/0.21.1"
		},
		"params": {},
		"transformRequest": [null],
		"transformResponse": [null],
		"timeout": 0,
		"responseType": "json",
		"xsrfCookieName": "XSRF-TOKEN",
		"xsrfHeaderName": "X-XSRF-TOKEN",
		"maxContentLength": -1,
		"maxBodyLength": -1,
		"json": true
	},
	"code": "ECONNREFUSED"
}
TypeError: Cannot read property 'statusText' of undefined
    at Client.call (/usr/local/src/node_modules/node-appwrite/lib/client.js:167:64)
    at processTicksAndRejections (node:internal/process/task_queues:93:5)
    at async Database.listDocuments (/usr/local/src/node_modules/node-appwrite/lib/services/database.js:246:16)

For accessing your Appwrite instance from within the function runtime you could use: http://host.docker.internal/v1 as the Appwrite endpoint.

i got fix this bug with setEndpoint to local ip address, while try using http://host.docker.internal/v1 execution always waiting

I noticed this same error when executing a Node 16 function from the admin console, as soon as that function tries to list documents in a collection. This happens regardless of the endpoint I set in the client (IP address, localhost, or host.docker.internal) and using HTTP, or using HTTPS combined with setSelfSigned(true). I've only noticed this from a Docker installation on Windows, after successfully using the same function with an installation on 2 different Macs. I tried turning Windows Firewall off and accepted all defaults on the Appwrite installation, so the .env and docker-compose.yaml file are the default values for a new installation of 0.9.1.

When I replace the call function's catch block in client.js with console.error(error), this is the result:

e,
      decodeStrings: true,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,
      buffered: [],
      bufferedIndex: 0,
      allBuffers: true,
      allNoop: true,
      pendingcb: 0,
      constructed: true,
      prefinished: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: true,
      errored: null,
      closed: false,
      closeEmitted: false,
      [Symbol(kOnFinished)]: []
    },
    _events: [Object: null prototype] {
      response: [Function: handleResponse],
      error: [Function: handleRequestError]
    },
    _eventsCount: 2,
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: 10485760,
      protocol: 'http:',
      path: '/v1/database/collections/60f723eeb608c/documents?limit=1&offset=0&orderField=date&orderType=DESC',
      method: 'GET',
      headers: [Object],
      agent: undefined,
      agents: [Object],
      auth: undefined,
      hostname: 'localhost',
      port: null,
      nativeProtocols: [Object],
      pathname: '/v1/database/collections/60f723eeb608c/documents',
      search: '?limit=1&offset=0&orderField=date&orderType=DESC'
    },
    _ended: true,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 0,
    _requestBodyBuffers: [],
    _onNativeResponse: [Function (anonymous)],
    _currentRequest: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      _closed: false,
      socket: [Socket],
      _header: 'GET /v1/database/collections/60f723eeb608c/documents?limit=1&offset=0&orderField=date&orderType=DESC HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'x-sdk-version: appwrite:nodejs:2.4.0\r\n' +
        'X-Appwrite-Response-Format: 0.9.0\r\n' +
        'x-appwrite-project: 60f723bebd262\r\n' +
        'x-appwrite-key: [OMITTED]\r\n' +
        'Content-Type: application/json\r\n' +
        'User-Agent: axios/0.21.1\r\n' +
        'Host: localhost\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/v1/database/collections/60f723eeb608c/documents?limit=1&offset=0&orderField=date&orderType=DESC',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'localhost',
      protocol: 'http:',
      _redirectable: [Circular *1],
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    _currentUrl: 'http://localhost/v1/database/collections/60f723eeb608c/documents?limit=1&offset=0&orderField=date&orderType=DESC',
    [Symbol(kCapture)]: false
  },
  response: undefined,
  isAxiosError: true,
  toJSON: [Function: toJSON]
}
An error occurred.

Prior to removing the exception throwing from the catch block, my result was this:

Error:  TypeError: Cannot read property 'statusText' of undefined
    at Client.call (/usr/local/src/node_modules/node-appwrite/lib/client.js:163:64)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Database.listDocuments (/usr/local/src/node_modules/node-appwrite/lib/services/database.js:246:16)
    at async downloadObjects (file:///usr/local/src/index.js:92:24)
    at async main (file:///usr/local/src/index.js:231:17)

You can see that the response property is in the error, but undefined, which explains the TypeError for statusText:

throw new AppwriteException(error.response.statusText, error.response.status, error.response.data);

Also, when using the same URL and headers in Postman, I see the correct response:

{
    "sum": 0,
    "documents": []
}

I'm still at a loss as to why the call is failing in the first place, and where I would go about debugging that. Thanks in advance for any assistance!


Appwrite Version: 0.9.1.149

Closing this as there's been no new activity for long time, feel free to reopen if the issue still exist.