Skip to content

Commit

Permalink
Merge pull request #83 from contentstack/fileField-bugFix
Browse files Browse the repository at this point in the history
bugfix for file fields in groups and modular blocks
  • Loading branch information
Ninad Hatkar authored Feb 15, 2021
2 parents a0a4390 + e942cdc commit 795ff90
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 166 deletions.
86 changes: 32 additions & 54 deletions gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ var _defineProperty2 = require('babel-runtime/helpers/defineProperty');

var _defineProperty3 = _interopRequireDefault(_defineProperty2);

var _extends4 = require('babel-runtime/helpers/extends');
var _extends5 = require('babel-runtime/helpers/extends');

var _extends5 = _interopRequireDefault(_extends4);
var _extends6 = _interopRequireDefault(_extends5);

var _set = require('babel-runtime/core-js/set');

Expand Down Expand Up @@ -45,6 +45,7 @@ var downloadAssets = require('./download-assets');

var references = [];
var groups = [];
var fileFields = [];

exports.onPreBootstrap = function (_ref) {
var reporter = _ref.reporter;
Expand Down Expand Up @@ -94,9 +95,10 @@ exports.createSchemaCustomization = function () {
var contentTypeUid = contentType.uid.replace(/-/g, '_');
var name = typePrefix + '_' + contentTypeUid;
var extendedSchema = extendSchemaWithDefaultEntryFields(contentType.schema);
var result = buildCustomSchema(extendedSchema, [], [], [], name, typePrefix);
var result = buildCustomSchema(extendedSchema, [], [], [], [], name, typePrefix);
references = references.concat(result.references);
groups = groups.concat(result.groups);
fileFields = fileFields.concat(result.fileFields);
var typeDefs = ['type linktype{\n title: String\n href: String\n }', schema.buildObjectType({
name: name,
fields: result.fields,
Expand Down Expand Up @@ -305,7 +307,7 @@ exports.sourceNodes = function () {
});

if (!configOptions.downloadImages) {
_context2.next = 39;
_context2.next = 38;
break;
}

Expand All @@ -314,17 +316,16 @@ exports.sourceNodes = function () {
return downloadAssets({ cache: cache, getCache: getCache, createNode: createNode, createNodeId: createNodeId, getNodesByType: getNodesByType, reporter: reporter }, typePrefix, configOptions);

case 33:
_context2.next = 39;
_context2.next = 38;
break;

case 35:
_context2.prev = 35;
_context2.t1 = _context2['catch'](30);

console.log('error--->', _context2.t1);
reporter.info('Something went wrong while downloading assets. Details: ' + _context2.t1);

case 39:
case 38:

// deleting nodes

Expand Down Expand Up @@ -366,7 +367,7 @@ exports.sourceNodes = function () {
newState[typePrefix.toLowerCase() + '-sync-token-' + configOptions.api_key] = nextSyncToken;
setPluginStatus(newState);

case 48:
case 47:
case 'end':
return _context2.stop();
}
Expand All @@ -379,56 +380,33 @@ exports.sourceNodes = function () {
};
}();

// exports.onCreateNode = async ({
// cache,
// actions: { createNode },
// getCache,
// createNodeId,
// node,
// }, configOptions) => {
// // use a custom type prefix if specified
// const typePrefix = configOptions.type_prefix || 'Contentstack';

// // filter the images from all the assets
// // const regexp = new RegExp('https://(images).contentstack.io/v3/assets/')
// // const matches = regexp.exec(node.url);

// if (configOptions.downloadImages && node.internal.owner === 'gatsby-source-contentstack' && node.internal.type === `${typePrefix}_assets`) {
// const cachedNodeId = makeAssetNodeUid(node, createNodeId, typePrefix);

// const cachedFileNode = await cache.get(cachedNodeId);

// let fileNode;
// // Checks for cached fileNode
// if (cachedFileNode) {
// fileNode = cachedFileNode;
// } else {
// // create a FileNode in Gatsby that gatsby-transformer-sharp will create optimized images for
// fileNode = await createRemoteFileNode({
// // the url of the remote image to generate a node for
// url: encodeURI(node.url),
// getCache,
// createNode,
// createNodeId,
// parentNodeId: node.id,
// });

// if (fileNode)
// // Cache the fileNode, so it does not have to downloaded again
// await cache.set(cachedNodeId, fileNode);
// }

// if (fileNode)
// node.localAsset___NODE = fileNode.id;
// }
// };

exports.createResolvers = function (_ref7) {
var createResolvers = _ref7.createResolvers;

var resolvers = {};
fileFields.forEach(function (fileField) {
resolvers[fileField.parent] = (0, _extends6.default)({}, resolvers[fileField.parent], (0, _defineProperty3.default)({}, fileField.field.uid, {
resolve: function resolve(source, args, context, info) {
if (fileField.field.multiple && source[fileField.field.uid + '___NODE']) {
var nodesData = [];
source[fileField.field.uid + '___NODE'].forEach(function (id) {
context.nodeModel.getAllNodes().find(function (node) {
if (node.id === id) {
nodesData.push(node);
}
});
});
return nodesData;
} else {
return context.nodeModel.getAllNodes().find(function (node) {
return node.id === source[fileField.field.uid + '___NODE'];
});
}
}
}));
});
references.forEach(function (reference) {
resolvers[reference.parent] = (0, _extends5.default)({}, resolvers[reference.parent], (0, _defineProperty3.default)({}, reference.uid, {
resolvers[reference.parent] = (0, _extends6.default)({}, resolvers[reference.parent], (0, _defineProperty3.default)({}, reference.uid, {
resolve: function resolve(source, args, context, info) {
if (source[reference.uid + '___NODE']) {
var nodesData = [];
Expand All @@ -446,7 +424,7 @@ exports.createResolvers = function (_ref7) {
}));
});
groups.forEach(function (group) {
resolvers[group.parent] = (0, _extends5.default)({}, resolvers[group.parent], (0, _defineProperty3.default)({}, group.field.uid, {
resolvers[group.parent] = (0, _extends6.default)({}, resolvers[group.parent], (0, _defineProperty3.default)({}, group.field.uid, {
resolve: function resolve(source) {
if (group.field.multiple && !Array.isArray(source[group.field.uid])) {
return [];
Expand Down
51 changes: 16 additions & 35 deletions normalize.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,15 +191,15 @@ var builtEntry = function builtEntry(schema, entry, locale, entriesNodeIds, asse
return entryObj;
};

var buildBlockCustomSchema = function buildBlockCustomSchema(blocks, types, references, groups, parent, prefix) {
var buildBlockCustomSchema = function buildBlockCustomSchema(blocks, types, references, groups, fileFields, parent, prefix) {
var blockFields = {};
var blockType = 'type ' + parent + ' @infer {';

blocks.forEach(function (block) {
var newparent = parent.concat(block.uid);
blockType = blockType.concat(block.uid + ' : ' + newparent + ' ');

var _buildCustomSchema = buildCustomSchema(block.schema, types, references, groups, newparent, prefix),
var _buildCustomSchema = buildCustomSchema(block.schema, types, references, groups, fileFields, newparent, prefix),
fields = _buildCustomSchema.fields;

for (var key in fields) {
Expand Down Expand Up @@ -257,10 +257,11 @@ exports.extendSchemaWithDefaultEntryFields = function (schema) {
return schema;
};

var buildCustomSchema = exports.buildCustomSchema = function (schema, types, references, groups, parent, prefix) {
var buildCustomSchema = exports.buildCustomSchema = function (schema, types, references, groups, fileFields, parent, prefix) {
var fields = {};
groups = groups || [];
references = references || [];
fileFields = fileFields || [];
types = types || [];
schema.forEach(function (field) {
switch (field.data_type) {
Expand Down Expand Up @@ -361,49 +362,28 @@ var buildCustomSchema = exports.buildCustomSchema = function (schema, types, ref
case 'file':
var type = 'type ' + prefix + '_assets implements Node @infer { url: String }';
types.push(type);
fields[field.uid] = {
resolve: function resolve(source, args, context) {
if (field.multiple && source[field.uid + '___NODE']) {
var nodesData = [];
source[field.uid + '___NODE'].forEach(function (id) {
context.nodeModel.getAllNodes({
type: prefix + '_assets'
}).find(function (node) {
if (node.id === id) {
nodesData.push(node);
}
});
});
return nodesData;
}
fileFields.push({
parent: parent,
field: field
});

if (source[field.uid + '___NODE']) {
return context.nodeModel.getAllNodes({
type: prefix + '_assets'
}).find(function (node) {
return node.id === source[field.uid + '___NODE'];
});
}
return null;
}
};
if (field.mandatory) {
if (field.multiple) {
fields[field.uid].type = '[' + prefix + '_assets]!';
fields[field.uid] = '[' + prefix + '_assets]!';
} else {
fields[field.uid].type = prefix + '_assets!';
fields[field.uid] = prefix + '_assets!';
}
} else if (field.multiple) {
fields[field.uid].type = '[' + prefix + '_assets]';
fields[field.uid] = '[' + prefix + '_assets]';
} else {
fields[field.uid].type = prefix + '_assets';
fields[field.uid] = prefix + '_assets';
}
break;
case 'group':
case 'global_field':
var newparent = parent.concat('_', field.uid);

var result = buildCustomSchema(field.schema, types, references, groups, newparent, prefix);
var result = buildCustomSchema(field.schema, types, references, groups, fileFields, newparent, prefix);

for (var key in result.fields) {
if (Object.prototype.hasOwnProperty.call(result.fields[key], 'type')) {
Expand Down Expand Up @@ -439,7 +419,7 @@ var buildCustomSchema = exports.buildCustomSchema = function (schema, types, ref
case 'blocks':
var blockparent = parent.concat('_', field.uid);

var blockType = buildBlockCustomSchema(field.blocks, types, references, groups, blockparent, prefix);
var blockType = buildBlockCustomSchema(field.blocks, types, references, groups, fileFields, blockparent, prefix);

types.push(blockType);
if (field.mandatory) {
Expand Down Expand Up @@ -504,6 +484,7 @@ var buildCustomSchema = exports.buildCustomSchema = function (schema, types, ref
fields: fields,
types: types,
references: references,
groups: groups
groups: groups,
fileFields: fileFields
};
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "gatsby-source-contentstack",
"version": "2.3.1",
"version": "2.3.2",
"description": "Gatsby source plugin for building websites using Contentstack as a data source",
"scripts": {
"prepublish": "npm run build",
Expand Down
72 changes: 28 additions & 44 deletions src/gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const downloadAssets = require('./download-assets');

let references = [];
let groups = [];
let fileFields = [];

exports.onPreBootstrap = ({ reporter }) => {
const args = process.argv;
Expand Down Expand Up @@ -52,11 +53,13 @@ exports.createSchemaCustomization = async ({
[],
[],
[],
[],
name,
typePrefix
);
references = references.concat(result.references);
groups = groups.concat(result.groups);
fileFields = fileFields.concat(result.fileFields);
const typeDefs = [
`type linktype{
title: String
Expand Down Expand Up @@ -261,7 +264,6 @@ exports.sourceNodes = async ({
try {
await downloadAssets({ cache, getCache, createNode, createNodeId, getNodesByType, reporter }, typePrefix, configOptions);
} catch (error) {
console.log('error--->', error);
reporter.info('Something went wrong while downloading assets. Details: ' + error);
}
}
Expand Down Expand Up @@ -333,52 +335,34 @@ exports.sourceNodes = async ({
setPluginStatus(newState);
};

// exports.onCreateNode = async ({
// cache,
// actions: { createNode },
// getCache,
// createNodeId,
// node,
// }, configOptions) => {
// // use a custom type prefix if specified
// const typePrefix = configOptions.type_prefix || 'Contentstack';

// // filter the images from all the assets
// // const regexp = new RegExp('https://(images).contentstack.io/v3/assets/')
// // const matches = regexp.exec(node.url);

// if (configOptions.downloadImages && node.internal.owner === 'gatsby-source-contentstack' && node.internal.type === `${typePrefix}_assets`) {
// const cachedNodeId = makeAssetNodeUid(node, createNodeId, typePrefix);

// const cachedFileNode = await cache.get(cachedNodeId);

// let fileNode;
// // Checks for cached fileNode
// if (cachedFileNode) {
// fileNode = cachedFileNode;
// } else {
// // create a FileNode in Gatsby that gatsby-transformer-sharp will create optimized images for
// fileNode = await createRemoteFileNode({
// // the url of the remote image to generate a node for
// url: encodeURI(node.url),
// getCache,
// createNode,
// createNodeId,
// parentNodeId: node.id,
// });

// if (fileNode)
// // Cache the fileNode, so it does not have to downloaded again
// await cache.set(cachedNodeId, fileNode);
// }

// if (fileNode)
// node.localAsset___NODE = fileNode.id;
// }
// };

exports.createResolvers = ({ createResolvers }) => {
const resolvers = {};
fileFields.forEach(fileField => {
resolvers[fileField.parent] = {
...resolvers[fileField.parent],
... {
[fileField.field.uid]: {
resolve(source, args, context, info) {
if (fileField.field.multiple && source[`${fileField.field.uid}___NODE`]) {
const nodesData = [];
source[`${fileField.field.uid}___NODE`].forEach(id => {
context.nodeModel.getAllNodes().find(node => {
if (node.id === id) {
nodesData.push(node);
}
});
});
return nodesData;
} else {
return context.nodeModel.getAllNodes().find(
node => node.id === source[`${fileField.field.uid}___NODE`])
}
},
},
}
};
})
references.forEach(reference => {
resolvers[reference.parent] = {
...resolvers[reference.parent],
Expand Down
Loading

0 comments on commit 795ff90

Please sign in to comment.