add blog posts to graphql

This commit is contained in:
Jonas Leder 2022-03-08 11:05:52 +01:00
parent d1cda0ba2f
commit bd9be3b0b5
No known key found for this signature in database
GPG key ID: 8A53DD45A7D7B44B
4 changed files with 52 additions and 25 deletions

View file

@ -1,24 +0,0 @@
<?php
include "./lib/config.php";
include "./lib/mysql.php";
$id = $conn->real_escape_string($_GET["id"]);
$result = $conn->query("SELECT * FROM posts WHERE id=$id");
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
} else {
die("Post not found");
}
$title = $row["title"];
$content = $row["content"];
$date = $row["date"];
$id = $row["id"];
header('Content-Type: application/json');
echo json_encode([
"title" => $title,
"content" => $content,
"date" => $date,
"id" => $id
]);

View file

@ -17,7 +17,9 @@ $query = $input['query'];
$variableValues = isset($input['variables']) ? $input['variables'] : null;
try {
$rootValue = [];
$rootValue = [
"db"=> $conn
];
$result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
$output = $result->toArray();
} catch (\Exception $e) {

View file

@ -0,0 +1,41 @@
<?php
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\ObjectType;
$blogPostFields = new ObjectType([
"name" => "Blog",
"fields" => [
"title" => Type::string(),
"content" => Type::string(),
"date" => Type::string(),
"id" => Type::string(),
"error" => Type::string(),
],
]);
function blogPost($id, $conn)
{
$id = $conn->real_escape_string($id);
$result = $conn->query("SELECT * FROM posts WHERE id=$id");
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
} else {
return [
"error" => "Post not found"
];
}
$title = $row["title"];
$content = $row["content"];
$date = $row["date"];
$id = $row["id"];
return [
"title" => $title,
"content" => $content,
"date" => $date,
"id" => $id,
"error" => ""
];
}

View file

@ -3,6 +3,7 @@ use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
require "./queries/skills.php";
require "./queries/blogPost.php";
$queryType = new ObjectType([
'name' => 'Query',
@ -15,5 +16,12 @@ $queryType = new ObjectType([
'type' => Type::listOf(Type::string()),
'resolve' => fn ($rootValue, $args) => getSkills(),
],
'blogPost' => [
"type" => $blogPostFields,
'args' => [
'id' => Type::nonNull(Type::string()),
],
'resolve' => fn ($rootValue, $args) => blogPost($args["id"], $rootValue["db"]),
],
],
]);