【问题标题】:My API returns response the second time it's called [closed]我的 API 在第二次调用时返回响应 [关闭]
【发布时间】:2018-09-18 16:44:20
【问题描述】:

我正在制作一个简单的 API 端点,它返回事件的访问代码。

如果事件没有访问代码,则应为其分配一个。然后,它检查它当前是公共的还是私有的。如果是私有的,返回访问代码,如果是公共的,返回空字符串。

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

我的问题是,对于为空的私人事件,它仅在第二次调用时返回访问代码(在邮递员上测试过)。这不是适当的 API 行为。

【问题讨论】:

  • 哦,很高兴知道。最好把状态更新。

标签: php api laravel-5 endpoint


【解决方案1】:

问题是$event 对象没有自动更新。

首先你尝试查询一个事件,如果它不存在你创建一个,但是你需要再次查询它。

所以在你的if ($event->access_code == null) { 部分,最后你需要再次从数据库加载事件:

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

希望对你有帮助

编辑:

我最初的假设是错误的,即我认为(出于某种原因)整个记录都丢失了,并且您创建了一个新的事件行。那是假的。 无论是否有访问代码,事件记录都应具有privacy 设置。

我怀疑,你的问题不在这里(在这个类中),它应该是逻辑中的其他错误 - 例如 api->getEventForce 不返回没有访问代码的事件。

尝试在查询后立即打印事件对象;我怀疑这将是一个空结果

【讨论】:

  • 您的第一张照片并不完全准确,但再次加载事件仍然有效。我打印了该事件,无论 access_code 为空还是有数字,它都会返回。谢谢!
猜你喜欢
  • 2019-12-09
  • 1970-01-01
  • 2020-04-13
  • 2010-11-29
  • 2020-10-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多