Skip to content
Advertisement

My API returns response the second time it’s called [closed]

I’m making a simple API endpoint that returns an access code for an event.

If the event does not have access code, then it should be assigned one. Then, it checks if it’s currently public or private. If private, return access code, if public, return empty string.

public function getAc($eventId) {
    // Pull event
    $event = $this->eventService->api->getEventForce($eventId);


    // If no access code for the event, generate one and update event record accordingly
    if ($event->access_code == null) {
        $access_code = $this->generateAccessCode();
        $affected = DB::update('update events set access_code = ? where id = ?', [$access_code, $eventId]);
    }

    // Is the event currently private? return access code
    if ($event->privacy=='private') {
        return $event->access_code;
    }

    // Is it public ? return empty string.
    else {
        return '';
    }
}

My problem is that for private events that were null, it only returns the access code the second time it’s called (as tested on postman). which isn’t appropriate API behaviour.

Advertisement

Answer

The problem is that the $event object doesn’t get updated automatically.

First you try query an event, and if it doesn’t exist you create one, but then you need to query it again.

So in your if ($event->access_code == null) { part, at the end you’ll need to load the event from the db again:

public function getAc($eventId) {
    // Pull event
    $event = $this->eventService->api->getEventForce($eventId);

    // If no access code for the event, generate one and update event record accordingly
    if ($event->access_code == null) {
        $access_code = $this->generateAccessCode();
        $affected = DB::update('update events set access_code = ? where id = ?', [$access_code, $eventId]);
        // Pull event again
        $event = $this->eventService->api->getEventForce($eventId);
    }

    // Is the event currently private? return access code
    if ($event->privacy=='private') {
        return $event->access_code;
    }

    // Is it public ? return empty string.
    else {
        return '';
    }
}

Hope it helps

EDIT:

My initial assumption was wrong, that is I thought (for some reason) that the whole record is missing, and you create a new event row. Thats false. The event record should have a privacy setting regardless of having access code or not.

I suspect, that your problem is not here (in this class), it should be some other fault in the logic – for example the api->getEventForce doesn’t return events that doesn’t have an access code.

Try to print the event object right after the query; i suspect that it will be an empty result

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement