Skip to content

Commit

Permalink
Added database transactions that ensure changes are only committed be…
Browse files Browse the repository at this point in the history
…fore finally sending the response
  • Loading branch information
ezra-obiwale committed Oct 26, 2017
1 parent 8930692 commit b866004
Showing 1 changed file with 28 additions and 7 deletions.
35 changes: 28 additions & 7 deletions src/Controllers/Traits/Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use DB;

/**
* A colletion of methods to assist in quick controller generation
Expand Down Expand Up @@ -245,14 +246,21 @@ public function store(Request $request)

if ($resp = $this->beforeCreate($data)) return $resp;

DB::beginTransaction();
$data = is_object($model)
? $model->create($data)
: $model::create($data);

if (!$data) return $this->createFailedError();
if (!$data) {
DB::rollback();
return $this->createFailedError();
}

if ($resp = $this->beforeCreateResponse($data)) return $resp;
if ($resp = $this->beforeCreateResponse($data)) {
return $resp;
}

DB::commit();
return response()->json($data, 201);
}

Expand Down Expand Up @@ -295,11 +303,18 @@ public function update(Request $request, $id)

if ($resp = $this->beforeUpdate($data)) return $resp;

DB::beginTransaction();
$result = $item->update($data);

if (!$result) return $this->updateFailedError();
if (!$result) {
DB::rollback();
return $this->updateFailedError();
}

if ($resp = $this->beforeUpdateResponse($item)) return $resp;
if ($resp = $this->beforeUpdateResponse($item)) {
return $resp;
}
DB::commit();
return response()->json($item, 202);
}

Expand All @@ -319,10 +334,16 @@ public function destroy($id)

$this->beforeDelete($item);
$result = $item->delete();

if (!$result) {
DB::rollback();
return $this->deleteFailedError();
}

if (!$result) return $this->deleteFailedError();

if ($resp = $this->beforeDeleteResponse($item)) return $resp;
if ($resp = $this->beforeDeleteResponse($item)) {
return $resp;
}
DB::commit();
return response()->json($item, 202);
}
}

0 comments on commit b866004

Please sign in to comment.