Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSONAPI output improvement (assessment). #73

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/**
* @file
* Hooks JSON:API alter.
*/

use Symfony\Component\HttpFoundation\Response;

/**
* Alters the JSON:API response.
*
* @param array $jsonapi_response
* The decoded JSON data to be altered.
* @param \Symfony\Component\HttpFoundation\Response $response
* The response.
*/
function hook_jsonapi_assessment_alter(array &$jsonapi_response, Response $response) {

}

Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
name: JSONAPI Assessment
type: module
description: Drupal reactjs boilerplace Assessment
core: 8.x
package: Web services
dependencies:
- jsonapi:jsonapi

version: '8.x-1.0'
project: 'jsonapi'
datestamp: 1651580021
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

use Symfony\Component\HttpFoundation\Response;

/**
* Alters the JSON:API response.
*
* @param array $jsonapi_response
* The decoded JSON data to be altered.
* @param \Symfony\Component\HttpFoundation\Response $response
* The response.
*/
function jsonapi_assessment_jsonapi_response_alter(array &$jsonapi_response, Response $response) {
// loop data to alter
if (isset($jsonapi_response['data']) && is_Array($jsonapi_response['data'])) {
$entity_manager = \Drupal::entityTypeManager();
$access_handler = $entity_manager->getAccessControlHandler('node');
$access = $access_handler->createAccess('article');

foreach ($jsonapi_response['data'] as $key => $item) {
if ($item['type'] == 'articles') {
$jsonapi_response['data'][$key]['attributes']['editable'] = $access; // append attributes to display edit link in front end.
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
services:
jsonapi_assessment.response_subscriber:
class: Drupal\jsonapi_assessment\EventSubscriber\ResponseSubscriber
arguments: [ '@module_handler' ]
tags:
- { name: event_subscriber }
calls:
- [ setRouteMatch, [ '@current_route_match' ] ]
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
<?php

namespace Drupal\jsonapi_assessment\EventSubscriber;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\jsonapi\Routing\Routes;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
* Class ResponseSubscriber.
*
* Implements the alter hook for JSON:API responses.
*
* @package Drupal\jsonapi_assessment\EventSubscriber
*/
class ResponseSubscriber implements EventSubscriberInterface, ContainerInjectionInterface {

/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;

/**
* The route match service.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
protected $routeMatch;

/**
* ResponseSubscriber constructor.
*
* @param \Drupal\Core\Extension\ModuleHandlerInterface $moduleHandler
* The module handler.
*/
public function __construct(ModuleHandlerInterface $moduleHandler) {
$this->moduleHandler = $moduleHandler;
}

/**
* Create a new instance.
*
* @param \Symfony\Component\DependencyInjection\ContainerInterface $container
* The container.
*
* @return \Drupal\jsonapi_assessment\EventSubscriber\ResponseSubscriber
* The new instance.
*/
public static function create(ContainerInterface $container) {
return new self(
$container->get('module_handler')
);
}

/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[KernelEvents::RESPONSE] = ['onResponse'];

return $events;
}

/**
* Set route match service.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match service.
*/
public function setRouteMatch(RouteMatchInterface $route_match) {
$this->routeMatch = $route_match;
}

/**
* This method is called the KernelEvents::RESPONSE event is dispatched.
*
* @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
* The filter event.
*/
public function onResponse(FilterResponseEvent $event) {
if (!$this->routeMatch->getRouteObject()) {
return;
}

if (
$this->routeMatch->getRouteName() === 'jsonapi.resource_list' ||
Routes::isJsonApiRequest($this->routeMatch->getRouteObject()
->getDefaults())
) {

$response = $event->getResponse();
$content = $response->getContent();

$jsonapi_response = json_decode($content, TRUE);

if (!is_array($jsonapi_response)) {
return;
}

// call the hook aler
$this->moduleHandler->alter('jsonapi_response', $jsonapi_response, $response);
$response->setContent(json_encode($jsonapi_response));
}
}

}
27 changes: 26 additions & 1 deletion react/api/article.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ import request from '../utils/request';
*/
export const getAll = () => new Promise((resolve, reject) => {
request
.get('/api/articles')
.get('/api/articles/')
.query({
'fields[node--article]': 'id',
'include': 'image'
})
// Tell superagent to consider any valid Drupal response as successful.
// Later we can capture error codes if needed.
Expand All @@ -28,3 +29,27 @@ export const getAll = () => new Promise((resolve, reject) => {
reject(error);
});
});

export const getById = (id) => new Promise((resolve, reject) => {
console.log(id);
request
.get('/api/articles/' + id)
.query({
})
// Tell superagent to consider any valid Drupal response as successful.
// Later we can capture error codes if needed.
.ok((resp) => resp.statusCode)
.then((response) => {
console.log(response.body);
resolve({
// eslint-disable-next-line max-len
article: response.statusCode === 200 ? transforms.articleDetail(response.body.data) : {},
statusCode: response.statusCode,
});
})
.catch((error) => {
// eslint-disable-next-line no-console
console.error('Could not fetch the article detail.', error);
reject(error);
});
});
15 changes: 13 additions & 2 deletions react/pages/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react';
import PropTypes from 'prop-types';
import * as articleApi from '../api/article';
import Link from "next/link"

class HomePage extends React.Component {
static async getInitialProps() {
Expand All @@ -15,6 +16,7 @@ class HomePage extends React.Component {
} catch (e) {
// Pass status code as internal properly. It is being checked inside of
// render() method of _app.js.
console.log(e);
initialProps.statusCode = 500;
}

Expand All @@ -23,12 +25,19 @@ class HomePage extends React.Component {

render() {
const { articles } = this.props;

return (
<div>
Home page is working!<br /><br />
List of articles from Drupal:<br />
<ul>
{articles.map((article) => <li key={article.id}>{article.title} (id: {article.id})</li>)}
{articles.map((article) => <li key={article.id}>
<Link href={{ pathname: "/article/" + article.id }}>
<a>{article.title}</a>
</Link> {console.log(article)}
{ article.editable ? <Link className="edit-link" href={{ pathname: "/article/" + article.id + "/edit"}}> [Edit]</Link> : ''}
</li>)
}
</ul>
</div>
);
Expand All @@ -37,8 +46,10 @@ class HomePage extends React.Component {

HomePage.propTypes = {
articles: PropTypes.arrayOf(PropTypes.shape({
title: PropTypes.string,
id: PropTypes.string,
title: PropTypes.string,
body: PropTypes.string,
editable: PropTypes.bool
})),
};

Expand Down