Perché il cloud funzione continua a dare un errore (CloudFirestore con ForOf Loop)?

0

Domanda

La mia funzione getDocuments() in sintesi, consiste nel fatto che ho il superamento di alcuni parametri in un array (come il percorso, il nome del documento, se voglio sezione di parti) e sulla base di tale matrice restituisce il contenuto di ciascun documento all'interno di un ciclo (ForOf), la funzione e lo faccio più che altro per non farmi troppe righe di codice, il problema è che non sempre mi butta un errore che non so di cosa si tratta.

Mi potete aiutare? Si prega di

Cloud funzione

export const employees = functions.https.onRequest((request, response) => {
corsHandler(request, response, async () => {
    return await security.securityLayer(
        { _definedMethod: "GET", userValue: request.method },
        { _definedType: true, _definedLevel: [4], _definedSeconds: 12, userToken: request.header("_token") },
        { required: false },
        { required: false }
    ).then(async (answer) => {
        if (answer.status === 400 || answer.status === 401) {
            return response.status(answer.status).send(answer);
        }

        return await security.getDocuments([
            { collection: "Core/", documentName: "Centers", options: { idReturn: "centros", nestedProperties: [] } },
            {
                collection: "Core/", documentName: "Employees", options: {
                    idReturn: "personal",
                    nestedProperties: [
                          { idReturn: "employees", name: "employee" },
                          { idReturn: "submanager", name: "submanager" },
                          { idReturn: "manager", name: "manager" }
                     ],
                },
            },
        ], SPECIAL_CODE).then((documents) => response.status(documents.status).send(documents))
            .catch(() => response.status(500).send(security.error500(SPECIAL_CODE, 2)));
    }).catch(() => response.status(500).send(security.error500("SPECIAL_CODE", 1)));
});
});

funzione async

export async function getDocuments(
documents: {
    collection: string,
    documentName: string,
    options: {
        idReturn: string,
        nestedProperties: {
            idReturn: string,
            name: string
        }[]
    }
}[],
code: string):
Promise<{ status: 201, code: string, subcode: number, devDescription: string, data: any }> {
const data: any = {};
const response: { devDescription: string, subcode: number } = { devDescription: "The document was found and retrieved successfully.", subcode: 1 };

if (documents.length > 1) {
    response.devDescription = "Documents were found and obtained successfully.";
    response.subcode = 2;
}

for (const iterator of documents) {
    const docRef = { path: iterator.collection, name: iterator.documentName };
    const options = { id: iterator.options.idReturn, nestedProperties: iterator.options.nestedProperties };
    const doc = await database.collection(docRef.path).doc(docRef.name).get();

    if (!doc.exists) {
        data[options.id] = "The document " + docRef.name + " does not exist in the specified path: " + docRef.path;

        if (documents.length === 1) {
            response.devDescription = "The document was not found. Check the DATA for more information.";
            response.subcode = 3;
        } else {
            response.devDescription = "One, several or all documents were not found. Check the DATA for more information.";
            response.subcode = 3;
        }
    } else {
        const docData: any = doc.data();
        if (options.nestedProperties.length === 0) {
            data[options.id] = docData;
        } else {
            for (const nested of options.nestedProperties) {
                data[options.id][nested.idReturn] = _.get(docData, nested.name);
            }
        }
    }
}

return { status: 201, code: code, subcode: response.subcode, devDescription: response.devDescription, data: data };
}
firebase javascript node.js typescript
2021-11-23 20:10:26
1

Migliore risposta

0

Stavo studiando e ho visto che cosa stava causando l'errore è stato, ovviamente, il loop (ForOf), per risolvere ho utilizzato la Promessa.tutti() metodo, in modo che il codice effettivo che funziona per me è il seguente

export async function getDocuments(
documents: {
    collection: string,
    documentName: string,
    path?: string,
    options: {
        idReturn: string,
        nestedProperties: {
            idReturn: string,
            name: string
        }[]
    }
}[],
code: string):
Promise<{ status: number, code: string, subcode: number, devDescription: string, data: any }> {
const idPrimary: any = Object.values(
    documents.reduce((c: any, v: any) => {
        const k = v.options.idReturn;
        c[k] = c[k] || [];
        c[k].push(v);
        return c;
    }, {})
).reduce((c: any, v: any) => (v.length > 1 ? c.concat(v) : c), []);

if (idPrimary.length > 0) {
    return {
        status: 400, code: code, subcode: 0, data: idPrimary,
        devDescription: "Some return IDs are repeated, check your code and replace the return IDs with unique IDs, for more information see the DATA section." };
}

const response: { devDescription: string, subcode: number } = { devDescription: "The document was found and retrieved successfully.", subcode: 1 };
const queries = [];

if (documents.length > 1) {
    response.devDescription = "Documents were found and obtained successfully.";
    response.subcode = 2;
}

documents.map((document) => {
    if (document.path === undefined) {
        document.path = document.collection + "/" + document.documentName;
    }
});

for (const iterator of documents) {
    queries.push(database.collection(iterator.collection).doc(iterator.documentName).get());
}

return Promise.all(queries).then((snapShot) => {
    const data: any = {};
    snapShot.forEach((doc) => {
        const docProperties = documents.find((item) => item.path === doc.ref.path) ?? null;

        if (!doc.exists) {
            if (docProperties !== null) {
                data[docProperties.options.idReturn] = "The document " + doc.id + " does not exist in the specified path: " + doc.ref.path;

                if (documents.length === 1) {
                    response.devDescription = "The document was not found. Check the DATA for more information.";
                    response.subcode = 3;
                } else {
                    response.devDescription = "One, several or all documents were not found. Check the DATA for more information.";
                    response.subcode = 3;
                }
            }
        } else {
            if (docProperties !== null) {
                const docData: any = doc.data();
                if (docProperties.options.nestedProperties.length === 0) {
                    data[docProperties.options.idReturn] = docData;
                } else {
                    data[docProperties.options.idReturn] = {};
                    for (const nested of docProperties.options.nestedProperties) {
                        if (nested.name === undefined) {
                            data[docProperties.options.idReturn][nested.idReturn] = _.get(docData, nested.idReturn);
                        } else {
                            data[docProperties.options.idReturn][nested.idReturn] = _.get(docData, nested.name);
                        }
                    }
                }
            }
        }
    });
    return { status: 201, code: code, subcode: response.subcode, devDescription: response.devDescription, data: data };
});
}
2021-11-24 16:18:55

In altre lingue

Questa pagina è in altre lingue

Русский
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................