Почему моя облачная функция продолжает выдавать ошибку (CloudFirestore с циклом ForOf)?

0

Вопрос

Моя функция getDocuments() вкратце состоит в том, что я передаю некоторые параметры в массиве (например, путь, имя документа, если я хочу разделить его на части), и на основе этого массива я возвращаю содержимое каждого документа через цикл (для), функция, которую я делаю больше всего, чтобы сэкономить мне слишком много строк кода, проблема в том, что она всегда выдает мне ошибку, что я не знаю, что это такое.

Вы не могли бы мне помочь? Пожалуйста

Облачная функция

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)));
});
});

асинхронная функция

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

Лучший ответ

0

Я исследовал и увидел, что причиной ошибки, очевидно, был цикл (ForOf), для его решения я использовал метод Promise.all (), поэтому фактический код, который работает для меня, выглядит следующим образом

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

На других языках

Эта страница на других языках

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