Home > Software engineering >  How to check if database save and api call were successful?
How to check if database save and api call were successful?

Time:07-12

im currently writing a function which calls 2 other functions. Function 1 saves an object to a database, function 2 does an api call. The Api call looks like this:

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

And the DB action looks like this:

await this.dataService.TimesRepo.save(vacationDays)

This is a snippet of the function calling 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 want to send the response message if the two functions were decently executed. The attempt I have there right now cant be right, since it just checks if the functions exist at all.

Can you provide me an alternative? Greetings, Leo

CodePudding user response:

You should receive response of these 2 methods and then compare to validate if both are success or not probably as,

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.<any-property> && saveResponse.<any-property>) ? 'Vacation submitted' : 'Vacation could not be submitted'

You will have to identify <any-property> of response object which will have value based on success / fail. You can simply console.log() response objects to identify that <any-property> should use to compare.

CodePudding user response:

I created a new boolean which gets returned when the api call is done.

    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, status: true}

In the other function i can now check if the property status arrives with the stauts code true

  • Related