Guest User

Untitled

a guest
May 16th, 2018
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.56 KB | None | 0 0
  1. const get = require('lodash/get');
  2. const isNil = require('lodash/isNil');
  3. const omitBy = require('lodash/omitBy');
  4. const identity = require('lodash/identity');
  5. const { createImport } = require('../urls');
  6. const { listTableColumns } = require('./tableColumn');
  7.  
  8. const NO_MORE_INFORMATION = 'No more information available.';
  9.  
  10. const RESULT_TYPE_FAILED_INSERTING = 'FailedInserting';
  11. const RESULT_TYPE_FAILED_UPDATING = 'FailedUpdating';
  12. const RESULT_TYPE_SUCCESS_INSERTING = 'SuccessInserting';
  13. const RESULT_TYPE_SUCCESS_UPDATING = 'SuccessUpdating';
  14. const RESULT_TYPE_PRIMARY_KEY_VIOLATION = 'PrimaryKeyViolation';
  15. const RESULT_TYPE_FOREIGN_KEY_VIOLATION = 'ForeignKeyViolation';
  16. const RESULT_TYPE_COLUMN_MAPPING_FAILURE = 'ColumnMappingFailure';
  17. const RESULT_TYPE_COLUMNS_NOT_IN_TABLE = 'ColumnsNotInTable';
  18. const RESULT_TYPE_NO_REQUIRED_COLUMN_IN_TABLE = 'NoRequiredColumnInTable';
  19. const RESULT_TYPE_COLUMN_REQUIRED = 'ColumnRequired';
  20. const RESULT_TYPE_DUPLICATE_COLUMN_MAPPING = 'DuplicateColumnMapping';
  21. const RESULT_TYPE_NO_CHANGE_TO_EXISTING_CONTACT = 'NoChangeToExistingContact';
  22. const RESULT_TYPE_NOT_NULL_VIOLATION = 'NotNullViolation';
  23. const RESULT_TYPE_UNKNOWN = 'Unknown';
  24.  
  25. const RESULT_TYPES_ERROR = new Set([
  26. RESULT_TYPE_FAILED_INSERTING,
  27. RESULT_TYPE_FAILED_UPDATING,
  28. RESULT_TYPE_PRIMARY_KEY_VIOLATION,
  29. RESULT_TYPE_FOREIGN_KEY_VIOLATION,
  30. RESULT_TYPE_COLUMN_MAPPING_FAILURE,
  31. RESULT_TYPE_COLUMNS_NOT_IN_TABLE,
  32. RESULT_TYPE_NO_REQUIRED_COLUMN_IN_TABLE,
  33. RESULT_TYPE_COLUMN_REQUIRED,
  34. RESULT_TYPE_DUPLICATE_COLUMN_MAPPING,
  35. RESULT_TYPE_NOT_NULL_VIOLATION,
  36. RESULT_TYPE_UNKNOWN
  37. ]);
  38.  
  39. const omitEmpties = (obj) => omitBy(obj, isNil);
  40.  
  41. const DATA_TYPES_MAP = {
  42. 'Text': 'string',
  43. 'Long Text': 'string',
  44. 'Email Address': 'string',
  45. 'Date': 'datetime',
  46. 'Date Time': 'datetime'
  47. };
  48.  
  49. exports.generateColumnMappings = (z, bundle) =>
  50. Object.keys(bundle.inputData).reduce((memo, key) => {
  51. if (key.startsWith('columns.')) {
  52. memo.push({
  53. ColumnId: parseInt(key.slice(8)),
  54. Value: bundle.inputData[key]
  55. });
  56. }
  57. return memo;
  58. }, []);
  59.  
  60. exports.getTableInputFieldsFactory = (noun) => (z, bundle) => {
  61. const tableId = bundle.inputData.tableId;
  62. z.console.log('Getting columns for table: ' + tableId);
  63.  
  64. if (tableId == null) {
  65. return [];
  66. }
  67.  
  68. return listTableColumns(z, bundle)
  69. .then((columns) => columns.map((column) => ({
  70. key: 'rows.testing',
  71. label: 'rows.testing',
  72. required: !!column.isUnique,
  73. type: 'string'
  74. })));
  75. };
  76.  
  77. exports.createFactory = (requestFields, dataRecordFields) => (z, bundle) => {
  78. z.console.log(JSON.stringify(bundle, null, 4));
  79.  
  80. const fields = requestFields({
  81. ClientTableId: bundle.inputData.tableId,
  82. Type: bundle.inputData.type,
  83. FormatDate: bundle.inputData.dateFormat,
  84. Records: {
  85. DataRecord: [
  86. dataRecordFields({
  87. ColumnMappings: {
  88. ColumnMapping: exports.generateColumnMappings(z, bundle)
  89. }
  90. }, z, bundle)
  91. ]
  92. }
  93. }, z, bundle);
  94.  
  95. return z.request({
  96. method: 'POST',
  97. url: createImport(),
  98. body: omitEmpties(fields)
  99. })
  100.  
  101. // Check if the import failed by checking ImportTopLevel
  102. .then(response => {
  103. let resultType = get(response.json, ['ImportTopLevel', 0, 'ImportResultType']);
  104. if (RESULT_TYPES_ERROR.has(resultType)) {
  105. const failedImport = response.json.ImportDetails.find((i) => i.Result === resultType);
  106. if (failedImport) {
  107. throw new Error(`${resultType} Error (#${failedImport.Row}): ${failedImport.Response || NO_MORE_INFORMATION}`);
  108. }
  109.  
  110. throw new Error(`${resultType} Error: ${NO_MORE_INFORMATION}.`);
  111. }
  112.  
  113. return response;
  114. });
  115. };
  116.  
  117. exports.sampleFactory = (type) => ({
  118. tableId: 1,
  119. columns: [{
  120. id: 1,
  121. value: 'email@address.com'
  122. }]
  123. });
  124.  
  125. exports.default = ({
  126. key,
  127. noun,
  128. pluralNoun = `${noun}s`,
  129. tableNoun = 'Table',
  130. tableList,
  131. tableSearch,
  132. inputFields = identity,
  133. requestFields = identity,
  134. dataRecordFields = identity
  135. }) => ({
  136. key,
  137. noun,
  138.  
  139. create: {
  140. display: {
  141. label: `Create/Update ${pluralNoun}`,
  142. description: `Create or update one or multiple ${pluralNoun}.`
  143. },
  144. operation: {
  145. inputFields: inputFields([
  146. {
  147. key: 'type',
  148. required: true,
  149. label: 'Import type',
  150. choices: [{
  151. label: 'Insert',
  152. sample: `Creates a new ${noun} if a record with the same primary key does not exist, otherwise it will fail.`,
  153. value: 'Insert'
  154. }, {
  155. label: 'Update',
  156. sample: `Updates an existing ${noun} if a record with the same primary key exist, otherwise it will fail.`,
  157. value: 'Update',
  158. }, {
  159. label: 'Upsert',
  160. sample: `Updates an existing ${noun} if a record with the same primary key exist, otherwise it will create a new ${noun}`,
  161. value: 'Upsert'
  162. }]
  163. },
  164. { key: 'dateFormat', label: 'Date Format', type: 'string', required: false },
  165. {
  166. key: 'tableId',
  167. type: 'number',
  168. required: true,
  169. label: tableNoun,
  170. dynamic: tableList,
  171. search: tableSearch,
  172. altersDynamicFields: true
  173. },
  174. {
  175. key: 'rows',
  176. label: 'Rows',
  177. altersDynamicFields: true,
  178. children: [exports.getTableInputFieldsFactory(noun)]
  179. }
  180. ]),
  181. perform: exports.createFactory(requestFields, dataRecordFields),
  182. sample: exports.sampleFactory(key)
  183. }
  184. },
  185.  
  186. sample: exports.sampleFactory(key),
  187.  
  188. outputFields: [
  189. { key: 'id', label: 'ID' },
  190. { key: 'name', label: 'Name' }
  191. ]
  192. });
Add Comment
Please, Sign In to add comment