0

**In my crud project the admin adds the user in the docs as well as in auth by normal sdk would replace the current user so i tried admin sdk but writing the cloud functions and calling is getting complex as im new to firebase. i got this got from fellow stackoverflow's thread modified it for my convenience but doesn't seems to be working. **

I deployed the function locally using "firebase serve"

cloud function

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();


exports.createUser = functions.firestore
.document('Teamchers/{userId}')
.onCreate(async (snap, context) => {
    const userId = context.params.userId;
    const newUser = await admin.auth().createUser({
        disabled: false,
        username: snap.get('UserName'),
        email: snap.get('email'),
        password: snap.get('password'),
        subjectname: snap.get('subjectname')
    });
  
    return admin.firestore().collection('Teamchers').doc(userId).delete();
});

calling it

const createUser = firebase.functions().httpsCallable('createUser');

  const handleadd = async (e) =>{
    e.preventDefault();
    try{
      createUser({userData: data}).then(result => {
        console.log(data);
    });
      addDoc(collection(db, "Courses" , "Teachers", data.subjectname ), {
        ...data,
        timestamp: serverTimestamp(),
        
      });
      alert("Faculty added succesfully")
    } catch (e){
      console.log(e.message)
    }
  }
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • hello, i don't understand, why do you have a `return admin.firestore().collection('Teamchers').doc(userId).delete();` delete at the end of your return ? What kind of error do you have exaclty ? Or expected behaviour that you want to have ? – coderpolo Oct 16 '22 at 10:48
  • @coderpolo it is to delete the temp doc file. https://stackoverflow.com/a/51951046/20075210 heres the code – Dastagir Shaikh Oct 16 '22 at 10:52
  • oh okay i see what you try to do, is it normal that you have a typo in `.collection('Teamchers')`but you `addDoc(collection(db, "Courses" , "Teachers", data.subjectname )` ? – coderpolo Oct 16 '22 at 11:03
  • You have a typo in `exports.createUser = functions.firestore.document('Teamchers/{userId}').onCreate`: `Teamchers` instead of `Teachers`. – Frank van Puffelen Oct 16 '22 at 11:26
  • @coderpolo i corrected the typo but it doesnt seems to be solving the problem my whole page gets deprecated – Dastagir Shaikh Oct 16 '22 at 13:04

1 Answers1

1

In addition to the potential typo mentioned by coderpolo and Frank, there are several other errors in your codes:

1. JS SDK versions mixing-up

It seems that you are mixing up JS SDK V9 syntax with JS SDK V8 syntax.

Defining the Callable Cloud Function in your front-end as follows is V8 syntax:

const createUser = firebase.functions().httpsCallable('createUser'); 

While doing addDoc(collection(...)) is V9 syntax.

You have to choose one version of the JS SDK and unify your code (see V9 example below, #3).

2. Wrong Cloud Function definition

Defining your function with:

exports.createUser = functions.firestore
.document('Teamchers/{userId}')
.onCreate(async (snap, context) => {..})

is not the way you should define a Callable Cloud function.

With onCreate() you are defining a background triggered Cloud Function that is to be triggered when a new doc is created in Firestore and not a Callable CF.

You need to adapt it as follows:

exports.createUser = functions.https.onCall((data, context) => {

    try {
        // ....
        // Return data that can be JSON encoded
    } catch (e) {
        console.log(e.message)
        // !!!! See the doc: https://firebase.google.com/docs/functions/callable#handle_errors
    }
});

3. Use await since your handleadd() function is async

This is not stricto sensu an error but you should avoid using then() and async/await together.

I would refactor it as follows (V9 syntax):

import { getFunctions, httpsCallable } from "firebase/functions";

const functions = getFunctions();
const createUser = httpsCallable(functions, 'createUser');

const handleadd = async (e) => {
    e.preventDefault();
    try {
        await createUser({ userData: data })
        await addDoc(collection(db, "Courses", "Teachers", data.subjectname), {
            ...data,
            timestamp: serverTimestamp(),

        });
        alert("Faculty added succesfully")
    } catch (e) {
        console.log(e.message)
    }
}
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • im getting this error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-quantum-952d3.cloudfunctions.net/createUser. (Reason: CORS request did not succeed). Status code: (null). i deployed the function locally does this have to do with anything? – Dastagir Shaikh Oct 16 '22 at 13:43
  • It should be ok if you deploy it with `firebase deploy --only functions` instead of testing it with the emulator – Renaud Tarnec Oct 16 '22 at 13:46
  • isnt it requires blaze plan? it suppose to be only a small project so – Dastagir Shaikh Oct 16 '22 at 13:46
  • Yes it requires a Blaze plan. But it’s usually not expensive at all, see firebase.google.com/support/faq#functions-pricing and note that there is a free tier of 2M invocations per month. – Renaud Tarnec Oct 16 '22 at 13:58