Gurmukh Singh
Gurmukh Singh

Reputation: 2017

Firebase Cloud Function to delete user

We have a cloud function in my index.js:

const functions = require('firebase-functions');
const firebase_tools = require('firebase-tools');
const admin = require('firebase-admin');

admin.initializeApp();
 exports.deleteUser = functions.https.onCall((request, response) => { 

   const userId = request.params.userId;

   console.log('deleting user: ' + userId + ' ...');

   return firebase_tools.firestore
      .delete('messages/' + userId, {
        project: process.env.GCLOUD_PROJECT,
        recursive: true,
        yes: true,
        token: functions.config().fb.token
      }).then(  () => {
        return 'success';
      }
    ).catch( (error) => {
      console.log('Error deleting user messages: ', error);
    });
 });

In my swift code im calling it like so within my delete function:

func deleteUser() {
        
        let userId = Auth.auth().currentUser!.uid
        
        let url = URL(string: "https://us-central1-myapp.cloudfunctions.net/deleteUser?userId=\(userId)")!
        URLSession.shared.dataTask(with: url) { (data: Data?, response: URLResponse?, error: Error?) in
            if let data = data, let string = String(data: data, encoding: .utf8) {
                print("Delete user response:\n \(string)")
            } else {
                print("Deleting user failed:\n \(error?.localizedDescription ?? "N/A")")
            }
        }.resume()
        
    }

When executing im getting the following errors:

Request has invalid method. GET

And im getting the following message straight after the above error

Invalid request IncomingMessage {
  _readableState: 
   ReadableState {
     objectMode: false,
     highWaterMark: 16384,
     buffer: BufferList { head: null, tail: null, length: 0 },
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: null,
     ended: true,
     endEmitted: false,
     reading: false,
     sync: true,
     needReadable: false,
     emittedReadable: true,
     readableListening: false,
     resumeScheduled: false,
     destroyed: false,
     defaultEncoding: 'utf8',
     awaitDrain: 0,
     readingMore: true,
     decoder: null,
     encoding: null },
  readable: true,
  domain: null,
  _events: { end: [Function: resetHeadersTimeoutOnReqEnd] },
  _eventsCount: 1,
  _maxListeners: undefined,
  socket: 
   Socket {
     connecting: false,
     _hadError: false,
     _handle: 
      TCP {
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        onconnection: null,
        writeQueueSize: 0,
        _consumed: true },
     _parent: null,
     _host: null,
     _readableState: 
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [Object],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        destroyed: false,
        defaultEncoding: 'utf8',
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _events: 
      { end: [Array],
        _socketEnd: [Function: onSocketEnd],
        drain: [Array],
        timeout: [Function: socketOnTimeout],
        data: [Function: bound socketOnData],
        error: [Array],
        close: [Array],
        resume: [Function: onSocketResume],
        pause: [Function: onSocketPause] },
     _eventsCount: 9,
     _maxListeners: undefined,
     _writableState: 
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     allowHalfOpen: true,
     _bytesDispatched: 0,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server: 
      Server {
        domain: null,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _connections: 1,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 0,
        keepAliveTimeout: 5000,
        _pendingResponseData: 0,
        maxHeadersCount: null,
        headersTimeout: 40000,
        _connectionKey: '6::::8091',
        [Symbol(IncomingMessage)]: [Object],
        [Symbol(ServerResponse)]: [Object],
        [Symbol(asyncId)]: 4 },
     _server: 
      Server {
        domain: null,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _connections: 1,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 0,
        keepAliveTimeout: 5000,
        _pendingResponseData: 0,
        maxHeadersCount: null,
        headersTimeout: 40000,
        _connectionKey: '6::::8091',
        [Symbol(IncomingMessage)]: [Object],
        [Symbol(ServerResponse)]: [Object],
        [Symbol(asyncId)]: 4 },
     parser: 
      HTTPParser {
        '0': [Function: parserOnHeaders],
        '1': [Function: parserOnHeadersComplete],
        '2': [Function: parserOnBody],
        '3': [Function: parserOnMessageComplete],
        '4': [Function: bound onParserExecute],
        _headers: [],
        _url: '',
        _consumed: true,
        socket: [Circular],
        incoming: [Circular],
        outgoing: null,
        parsingHeadersStart: 0,
        maxHeaderPairs: 2000,
        onIncoming: [Function: bound parserOnIncoming],
        [Symbol(isReused)]: true },
     on: [Function: socketOnWrap],
     _paused: false,
     _httpMessage: 
      ServerResponse {
        domain: null,
        _events: [Object],
        _eventsCount: 2,

Im trying to call my delete function but keep getting these error? Im trying to call this cloud function to delete some data recursively.

Upvotes: 1

Views: 978

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

You've written a callable type function, but you're trying to invoke it with a standard HTTP request. This isn't going to work. If you want to use a callable on the backend, you'll need to use the provided client library to invoke it. Please see the documentation for examples.

If you are unable to use the client library, then you will have to implement the callable protocol yourself in the client.

If you want to implement a normal HTTP function that doesn't require a special protocol, you should not use a callable, and instead write an HTTP trigger.

Again, to be clear, callable functions are different than HTTP functions. Be sure to read the documentation and choose the one you want.

Upvotes: 4

Related Questions