Is there a way to verify if the database has been successfully saved and the API call has been

I am currently in the process of developing a function that calls two other functions. Function 1 is responsible for saving an object to a database, while function 2 performs an API call.

    async createMSCalendarEntry(start: Date, end: Date, name: string, userID: number, email: string) {
    const api_url = `https://graph.microsoft.com/v1.0/users/${vacationEmailforCalendar}/calendar/events`
    let graphresponse = await msRestNodeAuth.loginWithServicePrincipalSecret(`${microsoftClientIDforCalendar}`, `${microsoftSecretforCalendar}`, `${microsoftTenantIdforCalendar}`, { tokenAudience: "https://graph.microsoft.com/" })
    let token = await graphresponse.getToken()
    let newEvent = new Event(start.toISOString(), end.toISOString(), name, userID, email)
    var options = {
        url: api_url,
        json: newEvent.toGraphSchema(),
        method: "POST",
        headers: {
            'content-type': 'application/json',
            'Authorization': 'Bearer ' + token.accessToken
        }
    }
    let graphResponse = await this.doRequest(options)
    return (graphResponse)
}
async doRequest(options) {
    return new Promise(function (resolve, reject) {
        request(options, function (error, body) {
            if (error) {
                reject(error);
            }
            else {
                resolve(body);
            }
        });
    });
}

The DB action is as follows:

await this.dataService.TimesRepo.save(vacationDays)

This is just a snippet of the function that calls the other two:

            await this.createMSCalendarEntry(dates.start, dates.end, currentUser.FirstName, currentUser.Id, currentUser.Email)
            await this.dataService.TimesRepo.save(vacationDays)
            let responseMessage: string = (this.createMSCalendarEntry && this.dataService.TimesRepo.save) ? 'Vacation submitted' : 'Vacation could not be submitted'
            res.status(200).send({
                message: responseMessage,
                data: vacationDays
            })
            return
        }
        else {
            res.status(400).send("The selected vacation days are in an already planned vacation time!")
            return
        }

I need help creating a better check for ensuring the two functions were executed successfully, rather than just checking if they exist. Thanks, Leonidas

Answer №1

To ensure both methods are successful, you need to receive responses from them and compare the results. Here is a code snippet that demonstrates this:

const calendarResponse = await this.createMSCalendarEntry(dates.start, dates.end, currentUser.FirstName, currentUser.Id, currentUser.Email)
const saveResponse = await this.dataService.TimesRepo.save(vacationDays)
let responseMessage: string = (calendarResponse.success && saveResponse.success) ? 'Vacation submitted' : 'Vacation could not be submitted'

You should determine the specific property in the response object that indicates success or failure. Use console.log() to view the response objects and identify the property for comparison.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting a VueJS application with node/express into a single container using Docker

I may be treading on familiar ground here, but I haven't come across a solution that addresses my specific issue. I have a VueJS application running with Express/NodeJS as the server, and while I know the recommended approach is to separate them into ...

Conceal the toolbar element if it is not at the top of the page

I am encountering an issue with my toolbar. When I scroll down, the transparent background of the toolbar disappears and it looks like this: . How can I hide this component when the page is scrolled down and show it again when scrolling back up to the top ...

The Mongoose getter function is triggering error TS2590 by generating a union type that is too intricate to be displayed

I've come across the TS2590: Expression produces a union type that is too complex to represent error while trying to compile TypeScript. The issue seems to be connected to the id's getter function idFromString, as removing the id getter prevents ...

Stop automatic scrolling when the keyboard is visible in Angular

I have created a survey form where the user's name appears on top in mobile view. However, I am facing an issue with auto scroll when the keyboard pops up. I want to disable this feature to improve the user experience. <input (click)="onFocusI ...

Troubleshooting the Non-functioning req.value & ip with Node.js - Joi schema

I have implemented a joi schema to validate email and password that are sent as JSON in the request body. Now, I want to add an additional validation for the IP address. However, when I tried to do so, I encountered the following error: { "isJoi": tru ...

Tips for implementing a cascading dropdown feature in Angular 7 Reactive Formarray: Ensuring saved data loads correctly in the UI form

I recently found a helpful guide on stackoverflow related to creating cascading dropdowns in an Angular reactive FormArray, you can check it out here After following the instructions, I managed to achieve my desired outcome. However, I now face a new chal ...

Analyzing User Input and Database Information with Mongodb

Here's the HTML form I'm working with: <form id="contact-form" method="POST" action="/search"> <label for="company">Phone company</label> <input type="text" name="company" value=""> &l ...

Infinite Loop Issue in Angular2 RC5 when using the templateUrl

Encountering an issue with Angular2 RC5 that seems to be causing an infinite loop problem. The app.component, which is bootstrapped by the app.module, appears quite simple: @Component({ selector: 'my-app', template: `TEST` }) export cl ...

Tips for avoiding the return of JSON in AWS Lambda and AWS SAM when utilizing express.static

I have been working on building a serverless website using AWS Lambda and the SMA CLI tool from AWS. My main goal is to test making real requests to the API. Currently, I am facing an issue with serving assets using the express.static function. Whenever I ...

Revise the observable to trigger a NgbModal from a service

I have a situation in my Angular 11 service where I am using a Ngbmodal component to subscribe when it is closed. Below is the code snippet: showMessage(messageData: MessageDataDTO): Observable<MessageResult> { return new Observable((result) =&g ...

NestJS RabbitMQ Microservice Integration

Currently, I am attempting to establish a connection to a Rabbit MQ docker container through NestJS microservice. The setup involves running it using vagrant. Unfortunately, I keep encountering the following error: [1601171008162] ERROR (32761 on local): D ...

Create a TypeScript array of objects that mirrors a Java List<Map<String, String>>

In my Java function, the argument type is List<Map<String, String>>. To perform a fetch call from a TypeScript file, I need to declare a variable whose type corresponds to List<Map<String, String>>. As TypeScript does not have a bu ...

Are undefined Static Properties an Issue in Mocked Classes? (Jest)

Currently, I am facing a challenge in mocking a class that includes a static property. jest.mock("../../src/logger/index"); import { Logger } from "../../src/logger/index"; // .. const LoggerMock = Logger as jest.MockedClass<typeof ...

Tips for creating a custom waitForElementText function in Playwright

I need to implement a function called waitForElementText() in playwright. For example, I have headers labeled with the CSS selector '.header-name' on each page. When navigating from the Home page to the Users page, I provide two parameters to ...

Rearrange an element in an array from last to first position using typescript

I am working with an array that looks like this var column = ["generic complaint", "epidemic complaint", "epidemic1 complaint", "epidemic2 complaint", "bal vivah", "name"] My goal is to move the last element of the array to the first position, resultin ...

When using Reactjs, it is not possible to update the state using useState within the handleSubmit function

I've encountered a puzzling error and could use some assistance in understanding it better. After calling setServerList(data.data), the data still appears empty when I attempt to use it. export const KernelUpdateSearch = (props: RouteComponentProps) ...

Issue encountered while attempting to launch server using Node.js and Express

I am relatively new to backend development and encountered an issue yesterday while attempting to run my server. Here is the snippet of code where the error occurs: const express = require("express"); const app = express(); PORT = 8443; app.listen("POR ...

Exploring ways to loop through a large collection of data in MongoDB with over 100 items

Currently, I am utilizing the express and mongodb npm module to insert data into a collection containing more than 1300 items. The data is being extracted from a json file that also consists of over 1300 objects. The issue arises when using the code below ...

CSRF failure causes Supertest request to fail

Currently, my Express 4 application utilizes csurf for CSRF protection on API routes. The application runs smoothly and successfully enforces CSRF protection, displaying appropriate errors for requests lacking the csrf-token header. For testing purposes, ...

Attempting to retrieve response information through a specified URL

Exploring a simple concept where I am making a request from the front-end to fetch JSON data on the back-end. My tech stack involves ReactJS on the front-end and NodeJS/ExpressJS on the back-end. I'm a bit confused about the correct way to access JSO ...