Add actions to entity model
authorFrank Bessou <frank.bessou@logilab.fr>
Mon, 03 Apr 2017 11:16:23 +0200
changeset 65 14ee1973f839
parent 64 3e2e3705bd25
child 66 f4cbe104d9a6
Add actions to entity model
src/Api.js
src/model.js
--- a/src/Api.js	Mon Apr 03 10:54:29 2017 +0200
+++ b/src/Api.js	Mon Apr 03 11:16:23 2017 +0200
@@ -108,16 +108,42 @@
         const schemaPromise = this.getSchema(etype, eid);
         const fetchPromise = this.jsonFetchResponse(url);
         const dataPromise = fetchPromise.then( response => response.json() );
-        const entityPromise = Promise.all([schemaPromise, dataPromise]).then(([schema, data]) => {
-            const wrappedData = wrapEntityData(data, schema);
-            return {
-                url: url,
-                etype: etype,
-                eid: eid,
-                data: wrappedData,
-            };
+        const allowedActionsPromise = fetchPromise.then( response => this.extractAllowedActions(response) );
+
+        const entityPromise = Promise.all([schemaPromise, dataPromise, allowedActionsPromise]).then(
+                ([schema, data, allowedActions]) => {
+                    const wrappedData = wrapEntityData(data, schema);
+                    return {
+                        url: url,
+                        etype: etype,
+                        eid: eid,
+                        data: wrappedData,
+                        allowedActions: allowedActions,
+                    };
+                });
+        return entityPromise;
+    }
+
+    extractAllowedActions(response) {
+        if (!response.headers.has('Allow')) {
+            return ['view'];
+        }
+
+        const allowHeader = response.headers.get('Allow');
+        const allowedMethods = allowHeader.split(/[ ,]+/);
+        return allowedMethods.map((method) => {
+            switch(method) {
+                case 'POST':
+                    return 'create';
+                case 'GET':
+                    return 'view';
+                case 'PUT':
+                case 'PATCH':
+                    return 'edit';
+                case 'DELETE':
+                    return 'delete';
+            }
         });
-        return entityPromise;
     }
 
     createEntity(etype, attributes, ...files) {
--- a/src/model.js	Mon Apr 03 10:54:29 2017 +0200
+++ b/src/model.js	Mon Apr 03 11:16:23 2017 +0200
@@ -1,9 +1,18 @@
 import React from 'react';
 import {PropTypeJsonaryWrapper} from './jsonaryutils';
 
+
+export const PropTypeAction = React.PropTypes.oneOf([
+        'create',
+        'view',
+        'edit',
+        'delete',
+    ]);
+
 export const PropTypesEntityModel = React.PropTypes.shape({
     url: React.PropTypes.string.isRequired,
     etype: React.PropTypes.string.isRequired,
     eid: React.PropTypes.string.isRequired,
     data: PropTypeJsonaryWrapper.isRequired,
+    allowedActions: React.PropTypes.arrayOf(PropTypeAction).isRequired,
 });