A new Contentful powered blog

Oct 26, 2016 11:10

After Contentful sponsored Hackference this year - I was intrigued at just how easy it was to create a system that uses it.

I wasn't prepared for just how easy it was. From zero to a blog in less than an hour!

I am still 'caching' data in a database my end (mysql) as I am only on the free version, but by using the webhook system, it makes all of that super easy. I have the code on a Laravel installation - my favourite way of prototype quickly is to use Laravel to have the basics already there - and it was just oh so easy to get something running.

The main code is the webhook system - when a post is published, unpublished or changed it fires off a webhook to my system. The code for that bit is below.

//-- Grab raw data so we can grab type
$data = json_decode($request->getContent(), true);

//-- process
switch ($data['sys']['type'])
{
	case "Entry":
		//-- Post published
		$post = \App\Content::where('contentful_id', $data['sys']['id'])->first();
		if ($post == null)
		{
			//-- Create post
			$post = new \App\Content;
			$post->contentful_id = $data['sys']['id'];
		}

		//-- Lets re-do all content stuff
		$post->json = json_encode($data['fields']);
		$post->status = 1;
		$post->actual_created = $data['fields']['postDate']['en-US'];
		$post->save();
		break;

	case "DeletedEntry":
		//-- Post unpublished
		$post = \App\Content::where('contentful_id', $data['sys']['id'])->first();
		if ($post !== null) 
		{
			$post->status = 0;
			$post->save();
		}
		break;
}

return response()->json(['status' => 200]);

You can see I am still storing the fields in a JSON blob in the mysql database (thats bad - as it means querying that data is going to be a pain in the future) but overall, it really doesn't matter to me. Hopefully I will get some time to iterate and make it all a bit more friendlier in the coming weeks!