@dhis2/app-service-data
Advanced tools
Comparing version 3.11.3 to 3.12.0-alpha.1
"use strict"; | ||
var _react = require("@testing-library/react"); | ||
var React = _interopRequireWildcard(require("react")); | ||
var _react3 = require("../react"); | ||
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } | ||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } | ||
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } | ||
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } | ||
describe('<DataQuery />', () => { | ||
@@ -18,4 +13,3 @@ it('should render without failing', async () => { | ||
}; | ||
const wrapper = (_ref) => { | ||
const wrapper = _ref => { | ||
let { | ||
@@ -28,5 +22,4 @@ children | ||
}; | ||
const renderFunction = jest.fn(() => null); | ||
(0, _react.render)( /*#__PURE__*/React.createElement(_react3.DataQuery, { | ||
(0, _react.render)(/*#__PURE__*/React.createElement(_react3.DataQuery, { | ||
query: { | ||
@@ -61,4 +54,3 @@ answer: { | ||
}; | ||
const wrapper = (_ref2) => { | ||
const wrapper = _ref2 => { | ||
let { | ||
@@ -71,5 +63,4 @@ children | ||
}; | ||
const renderFunction = jest.fn(() => null); | ||
(0, _react.render)( /*#__PURE__*/React.createElement(_react3.DataQuery, { | ||
(0, _react.render)(/*#__PURE__*/React.createElement(_react3.DataQuery, { | ||
query: { | ||
@@ -76,0 +67,0 @@ test: { |
"use strict"; | ||
var _react = require("@testing-library/react"); | ||
var React = _interopRequireWildcard(require("react")); | ||
var _react3 = require("../react"); | ||
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } | ||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } | ||
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } | ||
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } | ||
describe('<DataMutation />', () => { | ||
@@ -26,4 +21,3 @@ it('should render without failing', async () => { | ||
}; | ||
const wrapper = (_ref) => { | ||
const wrapper = _ref => { | ||
let { | ||
@@ -36,5 +30,4 @@ children | ||
}; | ||
const renderSpy = jest.fn(() => null); | ||
(0, _react.render)( /*#__PURE__*/React.createElement(_react3.DataMutation, { | ||
(0, _react.render)(/*#__PURE__*/React.createElement(_react3.DataMutation, { | ||
mutation: mutation | ||
@@ -41,0 +34,0 @@ }, renderSpy), { |
@@ -7,11 +7,8 @@ "use strict"; | ||
exports.default = exports.DataEngine = void 0; | ||
var _getMutationFetchType = require("./helpers/getMutationFetchType"); | ||
var _resolveDynamicQuery = require("./helpers/resolveDynamicQuery"); | ||
var _validate = require("./helpers/validate"); | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
const reduceResponses = (responses, names) => responses.reduce((out, response, idx) => { | ||
@@ -21,10 +18,7 @@ out[names[idx]] = response; | ||
}, {}); | ||
class DataEngine { | ||
constructor(link) { | ||
_defineProperty(this, "link", void 0); | ||
this.link = link; | ||
} | ||
query(query) { | ||
@@ -53,3 +47,2 @@ let { | ||
} | ||
mutate(mutation) { | ||
@@ -76,7 +69,4 @@ let { | ||
} | ||
} | ||
exports.DataEngine = DataEngine; | ||
var _default = DataEngine; | ||
exports.default = _default; | ||
var _default = exports.default = DataEngine; |
"use strict"; | ||
var _DataEngine = require("./DataEngine"); | ||
const mockQuery = { | ||
@@ -20,3 +19,2 @@ test: { | ||
} | ||
return { | ||
@@ -23,0 +21,0 @@ type, |
@@ -7,5 +7,3 @@ "use strict"; | ||
exports.getMutationFetchType = void 0; | ||
const getMutationFetchType = mutation => mutation.type === 'update' ? mutation.partial ? 'update' : 'replace' : mutation.type; | ||
exports.getMutationFetchType = getMutationFetchType; |
"use strict"; | ||
var _getMutationFetchType = require("./getMutationFetchType"); | ||
describe('getMutationFetchType', () => { | ||
@@ -6,0 +5,0 @@ it('should return the passed fetch type if not `update`', () => { |
@@ -7,3 +7,2 @@ "use strict"; | ||
exports.resolveDynamicQuery = void 0; | ||
const resolveDynamicQuery = (_ref, variables) => { | ||
@@ -23,3 +22,2 @@ let { | ||
}; | ||
exports.resolveDynamicQuery = resolveDynamicQuery; |
"use strict"; | ||
var _resolveDynamicQuery = require("./resolveDynamicQuery"); | ||
describe('resolveDynamicQuery', () => { | ||
@@ -23,3 +22,3 @@ it('Should return an unmodified query if no dynamic properties exist', () => { | ||
resource: 'test', | ||
id: (_ref) => { | ||
id: _ref => { | ||
let { | ||
@@ -30,3 +29,3 @@ id | ||
}, | ||
params: (_ref2) => { | ||
params: _ref2 => { | ||
let { | ||
@@ -40,3 +39,3 @@ page | ||
}, | ||
data: (_ref3) => { | ||
data: _ref3 => { | ||
let { | ||
@@ -43,0 +42,0 @@ bar |
@@ -7,8 +7,5 @@ "use strict"; | ||
exports.validateResourceQuery = exports.validateResourceQueries = exports.getResourceQueryErrors = void 0; | ||
var _InvalidQueryError = require("../types/InvalidQueryError"); | ||
const validQueryKeys = ['resource', 'id', 'params', 'data']; | ||
const validTypes = ['read', 'create', 'update', 'replace', 'delete', 'json-patch']; | ||
const getResourceQueryErrors = (type, query) => { | ||
@@ -18,33 +15,24 @@ if (!validTypes.includes(type)) { | ||
} | ||
if (typeof query !== 'object') { | ||
return ['A query or mutation must be a javascript object']; | ||
} | ||
const errors = []; | ||
if (!query.resource || typeof query.resource !== 'string') { | ||
errors.push('Property resource must be a string'); | ||
} | ||
if (type === 'create' && query.id) { | ||
errors.push("Mutation type 'create' does not support property 'id'"); | ||
} | ||
if (query.id && typeof query.id !== 'string') { | ||
errors.push('Property id must be a string'); | ||
} | ||
if (query.params && typeof query.params !== 'object') { | ||
errors.push('Property params must be an object'); | ||
} | ||
if (type === 'delete' && query.data) { | ||
errors.push("Mutation type 'delete' does not support property 'data'"); | ||
} | ||
if (type === 'json-patch' && !Array.isArray(query.data)) { | ||
errors.push("Mutation type 'json-patch' requires property 'data' to be of type Array"); | ||
} | ||
const invalidKeys = Object.keys(query).filter(k => !validQueryKeys.includes(k)); | ||
@@ -56,8 +44,5 @@ invalidKeys.forEach(k => { | ||
}; | ||
exports.getResourceQueryErrors = getResourceQueryErrors; | ||
const validateResourceQueries = function (queries) { | ||
let names = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; | ||
if (names.length !== queries.length) { | ||
@@ -68,5 +53,3 @@ for (let i = names.length; i < queries.length; ++i) { | ||
} | ||
const errors = queries.reduce((errors, query, i) => errors.concat(getResourceQueryErrors('read', query).map(e => `[${names[i]}] ${e}`)), []); | ||
if (errors.length) { | ||
@@ -76,8 +59,5 @@ throw new _InvalidQueryError.InvalidQueryError(errors); | ||
}; | ||
exports.validateResourceQueries = validateResourceQueries; | ||
const validateResourceQuery = (type, query) => { | ||
const errors = getResourceQueryErrors(type, query); | ||
if (errors.length) { | ||
@@ -87,3 +67,2 @@ throw new _InvalidQueryError.InvalidQueryError(errors); | ||
}; | ||
exports.validateResourceQuery = validateResourceQuery; |
"use strict"; | ||
var _validate = require("./validate"); | ||
describe('query validation', () => { | ||
@@ -6,0 +5,0 @@ describe('getResourceQueryErrors', () => { |
@@ -6,5 +6,3 @@ "use strict"; | ||
}); | ||
var _DataEngine = require("./DataEngine"); | ||
Object.keys(_DataEngine).forEach(function (key) { | ||
@@ -20,5 +18,3 @@ if (key === "default" || key === "__esModule") return; | ||
}); | ||
var _DataEngineLink = require("./types/DataEngineLink"); | ||
Object.keys(_DataEngineLink).forEach(function (key) { | ||
@@ -34,5 +30,3 @@ if (key === "default" || key === "__esModule") return; | ||
}); | ||
var _ExecuteOptions = require("./types/ExecuteOptions"); | ||
Object.keys(_ExecuteOptions).forEach(function (key) { | ||
@@ -48,5 +42,3 @@ if (key === "default" || key === "__esModule") return; | ||
}); | ||
var _FetchError = require("./types/FetchError"); | ||
Object.keys(_FetchError).forEach(function (key) { | ||
@@ -62,5 +54,3 @@ if (key === "default" || key === "__esModule") return; | ||
}); | ||
var _JsonValue = require("./types/JsonValue"); | ||
Object.keys(_JsonValue).forEach(function (key) { | ||
@@ -76,5 +66,3 @@ if (key === "default" || key === "__esModule") return; | ||
}); | ||
var _Mutation = require("./types/Mutation"); | ||
Object.keys(_Mutation).forEach(function (key) { | ||
@@ -90,5 +78,3 @@ if (key === "default" || key === "__esModule") return; | ||
}); | ||
var _PossiblyDynamic = require("./types/PossiblyDynamic"); | ||
Object.keys(_PossiblyDynamic).forEach(function (key) { | ||
@@ -104,5 +90,3 @@ if (key === "default" || key === "__esModule") return; | ||
}); | ||
var _Query = require("./types/Query"); | ||
Object.keys(_Query).forEach(function (key) { | ||
@@ -118,5 +102,3 @@ if (key === "default" || key === "__esModule") return; | ||
}); | ||
var _QueryParameters = require("./types/QueryParameters"); | ||
Object.keys(_QueryParameters).forEach(function (key) { | ||
@@ -123,0 +105,0 @@ if (key === "default" || key === "__esModule") return; |
@@ -7,5 +7,5 @@ "use strict"; | ||
exports.FetchError = void 0; | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
class FetchError extends Error { | ||
@@ -19,13 +19,8 @@ constructor(_ref) { | ||
super(message); | ||
_defineProperty(this, "type", void 0); | ||
_defineProperty(this, "details", void 0); | ||
this.type = type; | ||
this.details = details; | ||
} | ||
} | ||
exports.FetchError = FetchError; |
"use strict"; | ||
var _FetchError = require("./FetchError"); | ||
describe('FetchError', () => { | ||
@@ -6,0 +5,0 @@ it('should construct successfully', () => { |
@@ -7,18 +7,13 @@ "use strict"; | ||
exports.InvalidQueryError = void 0; | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
class InvalidQueryError extends Error { | ||
constructor(errors) { | ||
super(`Invalid query\n${errors.map(e => ' - ' + e).join('\n')}`); | ||
_defineProperty(this, "type", 'invalid-query'); | ||
_defineProperty(this, "details", void 0); | ||
this.details = errors; | ||
} | ||
} | ||
exports.InvalidQueryError = InvalidQueryError; |
@@ -54,5 +54,3 @@ "use strict"; | ||
}); | ||
var _react = require("./react"); | ||
var _engine = require("./engine"); |
@@ -7,5 +7,5 @@ "use strict"; | ||
exports.CustomDataLink = void 0; | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
class CustomDataLink { | ||
@@ -17,9 +17,5 @@ constructor(customData) { | ||
} = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
_defineProperty(this, "failOnMiss", void 0); | ||
_defineProperty(this, "loadForever", void 0); | ||
_defineProperty(this, "data", void 0); | ||
this.data = customData; | ||
@@ -29,3 +25,2 @@ this.failOnMiss = failOnMiss; | ||
} | ||
async executeResourceQuery(type, query, options) { | ||
@@ -35,5 +30,3 @@ if (this.loadForever) { | ||
} | ||
const customResource = this.data[query.resource]; | ||
if (customResource === undefined) { | ||
@@ -43,6 +36,4 @@ if (this.failOnMiss) { | ||
} | ||
return Promise.resolve(null); | ||
} | ||
switch (typeof customResource) { | ||
@@ -54,11 +45,8 @@ case 'string': | ||
return customResource; | ||
case 'function': | ||
{ | ||
const result = await customResource(type, query, options); | ||
if (typeof result === 'undefined' && this.failOnMiss) { | ||
throw new Error(`The custom function for resource ${query.resource} must always return a value but returned ${result}`); | ||
} | ||
return result || null; | ||
@@ -68,5 +56,3 @@ } | ||
} | ||
} | ||
exports.CustomDataLink = CustomDataLink; |
"use strict"; | ||
var _CustomDataLink = require("./CustomDataLink"); | ||
describe('CustomDataLink', () => { | ||
@@ -6,0 +5,0 @@ it('Should return mocked resource', async () => { |
@@ -7,12 +7,10 @@ "use strict"; | ||
exports.ErrorLink = void 0; | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
class ErrorLink { | ||
constructor(errorMessage) { | ||
_defineProperty(this, "errorMessage", void 0); | ||
this.errorMessage = errorMessage; | ||
} | ||
executeResourceQuery() { | ||
@@ -22,5 +20,3 @@ console.error(this.errorMessage); | ||
} | ||
} | ||
exports.ErrorLink = ErrorLink; |
@@ -6,5 +6,3 @@ "use strict"; | ||
}); | ||
var _CustomDataLink = require("./CustomDataLink"); | ||
Object.keys(_CustomDataLink).forEach(function (key) { | ||
@@ -20,5 +18,3 @@ if (key === "default" || key === "__esModule") return; | ||
}); | ||
var _ErrorLink = require("./ErrorLink"); | ||
Object.keys(_ErrorLink).forEach(function (key) { | ||
@@ -34,5 +30,3 @@ if (key === "default" || key === "__esModule") return; | ||
}); | ||
var _RestAPILink = require("./RestAPILink"); | ||
Object.keys(_RestAPILink).forEach(function (key) { | ||
@@ -39,0 +33,0 @@ if (key === "default" || key === "__esModule") return; |
@@ -7,21 +7,14 @@ "use strict"; | ||
exports.RestAPILink = void 0; | ||
var _fetchData = require("./RestAPILink/fetchData"); | ||
var _path = require("./RestAPILink/path"); | ||
var _queryToRequestOptions = require("./RestAPILink/queryToRequestOptions"); | ||
var _queryToResourcePath = require("./RestAPILink/queryToResourcePath"); | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
class RestAPILink { | ||
constructor(config) { | ||
_defineProperty(this, "config", void 0); | ||
_defineProperty(this, "versionedApiPath", void 0); | ||
_defineProperty(this, "unversionedApiPath", void 0); | ||
this.config = config; | ||
@@ -31,7 +24,5 @@ this.versionedApiPath = (0, _path.joinPath)('api', String(config.apiVersion)); | ||
} | ||
fetch(path, options) { | ||
return (0, _fetchData.fetchData)((0, _path.joinPath)(this.config.baseUrl, path), options); | ||
} | ||
executeResourceQuery(type, query, _ref) { | ||
@@ -43,5 +34,3 @@ let { | ||
} | ||
} | ||
exports.RestAPILink = RestAPILink; |
"use strict"; | ||
var _fetchData = require("./RestAPILink/fetchData"); | ||
var _ = require("."); | ||
jest.mock('./RestAPILink/fetchData', () => ({ | ||
@@ -8,0 +6,0 @@ fetchData: jest.fn(async () => null) |
@@ -8,27 +8,21 @@ "use strict"; | ||
exports.parseStatus = exports.parseContentType = void 0; | ||
var _engine = require("../../engine"); | ||
const parseContentType = contentType => contentType ? contentType.split(';')[0].trim().toLowerCase() : ''; | ||
exports.parseContentType = parseContentType; | ||
const parseStatus = async response => { | ||
const accessError = response.status === 401 || response.status === 403 || response.status === 409; | ||
if (accessError) { | ||
let message; | ||
let details = {}; | ||
try { | ||
details = await response.json(); | ||
message = details.message; | ||
} catch (e) {// Do nothing | ||
} // Set a message in case of invalid json, or json without 'message' property | ||
} catch (e) { | ||
// Do nothing | ||
} | ||
// Set a message in case of invalid json, or json without 'message' property | ||
if (!message) { | ||
message = response.status === 401 ? 'Unauthorized' : 'Forbidden'; | ||
} | ||
throw new _engine.FetchError({ | ||
@@ -40,12 +34,10 @@ type: 'access', | ||
} | ||
if (response.status < 200 || response.status >= 400) { | ||
const message = `An unknown error occurred - ${response.statusText} (${response.status})`; | ||
let details = {}; | ||
try { | ||
details = await response.json(); | ||
} catch (e) {// We can leave details as is if parsing fails | ||
} catch (e) { | ||
// We can leave details as is if parsing fails | ||
} | ||
throw new _engine.FetchError({ | ||
@@ -57,11 +49,9 @@ type: 'unknown', | ||
} | ||
return response; | ||
}; | ||
exports.parseStatus = parseStatus; | ||
function fetchData(url) { | ||
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
return fetch(url, { ...options, | ||
return fetch(url, { | ||
...options, | ||
credentials: 'include', | ||
@@ -80,15 +70,15 @@ headers: { | ||
}).then(parseStatus).then(async response => { | ||
const contentType = parseContentType(response.headers.get('Content-Type')); // 'application/json' | ||
const contentType = parseContentType(response.headers.get('Content-Type')); | ||
// 'application/json' | ||
if (contentType === 'application/json') { | ||
return await response.json(); // Will throw if invalid JSON! | ||
} // 'text/*' | ||
} | ||
// 'text/*' | ||
if (/^text\/[a-z0-9.-]+$/.test(contentType)) { | ||
return await response.text(); | ||
} | ||
return await response.blob(); | ||
}); | ||
} |
"use strict"; | ||
var _engine = require("../../engine"); | ||
var _fetchData = require("./fetchData"); | ||
describe('networkFetch', () => { | ||
@@ -8,0 +6,0 @@ describe('parseContentType', () => { |
@@ -7,3 +7,2 @@ "use strict"; | ||
exports.normativeMetadataResources = exports.nonNormativeMetadataResources = void 0; | ||
/* | ||
@@ -14,9 +13,12 @@ * These are metadata resources (from /api/resources) which are known to support paging. | ||
*/ | ||
const normativeMetadataResources = ['programDataElements', 'indicatorTypes', 'programs', 'optionGroups', 'programRuleVariables', 'reports', 'users', 'constants', 'externalMapLayers', 'analyticsTableHooks', 'pushAnalysis', 'oAuth2Clients', 'validationRules', 'reportTables', 'userGroups', 'sqlViews', 'sections', 'validationNotificationTemplates', 'optionGroupSets', 'organisationUnitGroupSets', 'trackedEntityAttributes', 'dashboardItems', 'categoryCombos', 'programSections', 'trackedEntityTypes', 'dataSetNotificationTemplates', 'maps', 'dataApprovalWorkflows', 'programStages', 'categoryOptionGroups', 'relationshipTypes', 'validationRuleGroups', 'predictors', 'dataSets', 'options', 'organisationUnitLevels', 'dataEntryForms', 'predictorGroups', 'dataElementGroupSets', 'programIndicatorGroups', 'dataApprovalLevels', 'organisationUnits', 'programIndicators', 'dataElements', 'mapViews', 'categories', 'categoryOptionCombos', 'documents', 'indicators', 'optionSets', 'interpretations', 'programRuleActions', 'dataElementGroups', 'attributes', 'validationResults', 'categoryOptions', 'indicatorGroupSets', 'messageConversations', 'dashboards', 'programNotificationTemplates', 'programStageSections', 'legendSets', 'organisationUnitGroups', 'visualizations', 'indicatorGroups', 'programTrackedEntityAttributeGroups', 'programRules', 'categoryOptionGroupSets', 'userRoles', 'eventFilters', 'eventReports', 'eventCharts', 'smsCommands', 'jobConfigurations', 'minMaxDataElements', 'charts', 'dataElementOperands', // These exist and appear to accept field declarations, but have abnormal behavior when it comes to viewing collections and paging results | ||
'trackedEntityInstance', 'relationships']; // Including non-normative resources listed under /api/resources for future follow-up | ||
exports.normativeMetadataResources = normativeMetadataResources; | ||
const nonNormativeMetadataResources = ['trackedEntityAttributeValues', 'programInstances', 'expressions', 'programStageInstances', 'externalFileResources', 'icons', 'fileResources', 'metadataVersions', 'dataStores', // This doesn't exist, but is listed as the plural of 'dataStore' in /api/resources | ||
const normativeMetadataResources = exports.normativeMetadataResources = ['programDataElements', 'indicatorTypes', 'programs', 'optionGroups', 'programRuleVariables', 'reports', 'users', 'constants', 'externalMapLayers', 'analyticsTableHooks', 'pushAnalysis', 'oAuth2Clients', 'validationRules', 'reportTables', 'userGroups', 'sqlViews', 'sections', 'validationNotificationTemplates', 'optionGroupSets', 'organisationUnitGroupSets', 'trackedEntityAttributes', 'dashboardItems', 'categoryCombos', 'programSections', 'trackedEntityTypes', 'dataSetNotificationTemplates', 'maps', 'dataApprovalWorkflows', 'programStages', 'categoryOptionGroups', 'relationshipTypes', 'validationRuleGroups', 'predictors', 'dataSets', 'options', 'organisationUnitLevels', 'dataEntryForms', 'predictorGroups', 'dataElementGroupSets', 'programIndicatorGroups', 'dataApprovalLevels', 'organisationUnits', 'programIndicators', 'dataElements', 'mapViews', 'categories', 'categoryOptionCombos', 'documents', 'indicators', 'optionSets', 'interpretations', 'programRuleActions', 'dataElementGroups', 'attributes', 'validationResults', 'categoryOptions', 'indicatorGroupSets', 'messageConversations', 'dashboards', 'programNotificationTemplates', 'programStageSections', 'legendSets', 'organisationUnitGroups', 'visualizations', 'indicatorGroups', 'programTrackedEntityAttributeGroups', 'programRules', 'categoryOptionGroupSets', 'userRoles', 'eventFilters', 'eventReports', 'eventCharts', 'smsCommands', 'jobConfigurations', 'minMaxDataElements', 'charts', 'dataElementOperands', | ||
// These exist and appear to accept field declarations, but have abnormal behavior when it comes to viewing collections and paging results | ||
'trackedEntityInstance', 'relationships']; | ||
// Including non-normative resources listed under /api/resources for future follow-up | ||
const nonNormativeMetadataResources = exports.nonNormativeMetadataResources = ['trackedEntityAttributeValues', 'programInstances', 'expressions', 'programStageInstances', 'externalFileResources', 'icons', 'fileResources', 'metadataVersions', 'dataStores', | ||
// This doesn't exist, but is listed as the plural of 'dataStore' in /api/resources | ||
// Known but missing from /api/resources | ||
'userDataStore', 'apps']; | ||
exports.nonNormativeMetadataResources = nonNormativeMetadataResources; | ||
'userDataStore', 'apps']; |
@@ -7,3 +7,2 @@ "use strict"; | ||
exports.joinPath = void 0; | ||
const joinPath = function () { | ||
@@ -13,7 +12,5 @@ for (var _len = arguments.length, parts = new Array(_len), _key = 0; _key < _len; _key++) { | ||
} | ||
const realParts = parts.filter(part => !!part); | ||
return realParts.map(part => part.replace(/^\/+|\/+$/g, '')).join('/'); | ||
}; | ||
exports.joinPath = joinPath; |
"use strict"; | ||
var _path = require("./path"); | ||
describe('Utils', () => { | ||
@@ -6,0 +5,0 @@ describe('pathJoin', () => { |
@@ -7,5 +7,3 @@ "use strict"; | ||
exports.queryToRequestOptions = void 0; | ||
var _requestContentType = require("./queryToRequestOptions/requestContentType"); | ||
const getMethod = type => { | ||
@@ -15,16 +13,11 @@ switch (type) { | ||
return 'POST'; | ||
case 'read': | ||
return 'GET'; | ||
case 'update': | ||
case 'json-patch': | ||
return 'PATCH'; | ||
case 'replace': | ||
return 'PUT'; | ||
case 'delete': | ||
return 'DELETE'; | ||
default: | ||
@@ -34,3 +27,2 @@ throw new Error(`Unknown type ${type}`); | ||
}; | ||
const queryToRequestOptions = (type, query, signal) => { | ||
@@ -45,3 +37,2 @@ const contentType = (0, _requestContentType.requestContentType)(type, query); | ||
}; | ||
exports.queryToRequestOptions = queryToRequestOptions; |
"use strict"; | ||
var _queryToRequestOptions = require("./queryToRequestOptions"); | ||
describe('queryToRequestOptions', () => { | ||
@@ -6,0 +5,0 @@ it('should return a valid Fetch option object for read request', () => { |
@@ -7,3 +7,2 @@ "use strict"; | ||
exports.isStaticContentUpload = exports.isMessageConversationAttachment = exports.isFileResourceUpload = exports.isDataValue = exports.isAppInstall = void 0; | ||
/* | ||
@@ -14,2 +13,3 @@ * Requests that expect a "multipart/form-data" Content-Type have been collected by scanning | ||
*/ | ||
// Post to 'dataValues' (send/update a data value; endpoint doesn't support JSON) | ||
@@ -22,7 +22,6 @@ // For file-uploads too | ||
return type === 'create' && (resource === 'dataValues' || resource === 'dataValues/file'); | ||
}; // POST to 'fileResources' (upload a file resource) | ||
}; | ||
// POST to 'fileResources' (upload a file resource) | ||
exports.isDataValue = isDataValue; | ||
const isFileResourceUpload = (type, _ref2) => { | ||
@@ -33,7 +32,6 @@ let { | ||
return type === 'create' && resource === 'fileResources'; | ||
}; // POST to 'messageConversations/attachments' (upload a message conversation attachment) | ||
}; | ||
// POST to 'messageConversations/attachments' (upload a message conversation attachment) | ||
exports.isFileResourceUpload = isFileResourceUpload; | ||
const isMessageConversationAttachment = (type, _ref3) => { | ||
@@ -44,7 +42,6 @@ let { | ||
return type === 'create' && resource === 'messageConversations/attachments'; | ||
}; // POST to `staticContent/${key}` (upload staticContent: logo_banner | logo_front) | ||
}; | ||
// POST to `staticContent/${key}` (upload staticContent: logo_banner | logo_front) | ||
exports.isMessageConversationAttachment = isMessageConversationAttachment; | ||
const isStaticContentUpload = (type, _ref4) => { | ||
@@ -56,7 +53,6 @@ let { | ||
return type === 'create' && pattern.test(resource); | ||
}; // POST to 'apps' (install an app) | ||
}; | ||
// POST to 'apps' (install an app) | ||
exports.isStaticContentUpload = isStaticContentUpload; | ||
const isAppInstall = (type, _ref5) => { | ||
@@ -68,3 +64,2 @@ let { | ||
}; | ||
exports.isAppInstall = isAppInstall; |
"use strict"; | ||
var _multipartFormDataMatchers = require("./multipartFormDataMatchers"); | ||
describe('isDataValue', () => { | ||
@@ -6,0 +5,0 @@ it('returns true for a POST to "dataValues"', () => { |
@@ -7,26 +7,15 @@ "use strict"; | ||
exports.requestHeadersForContentType = exports.requestContentType = exports.requestBodyForContentType = void 0; | ||
var multipartFormDataMatchers = _interopRequireWildcard(require("./multipartFormDataMatchers")); | ||
var textPlainMatchers = _interopRequireWildcard(require("./textPlainMatchers")); | ||
var xWwwFormUrlencodedMatchers = _interopRequireWildcard(require("./xWwwFormUrlencodedMatchers")); | ||
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } | ||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } | ||
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } | ||
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } | ||
const resourceExpectsTextPlain = (type, query) => Object.values(textPlainMatchers).some(textPlainMatcher => textPlainMatcher(type, query)); | ||
const resourceExpectsMultipartFormData = (type, query) => Object.values(multipartFormDataMatchers).some(multipartFormDataMatcher => multipartFormDataMatcher(type, query)); | ||
const resourceExpectsXWwwFormUrlencoded = (type, query) => Object.values(xWwwFormUrlencodedMatchers).some(xWwwFormUrlencodedMatcher => xWwwFormUrlencodedMatcher(type, query)); | ||
const convertData = (data, initialValue) => { | ||
const dataEntries = Object.entries(data); | ||
if (dataEntries.length === 0) { | ||
throw new Error(`Could not convert data to ${initialValue.constructor.name}: object does not have own enumerable string-keyed properties`); | ||
} | ||
return dataEntries.reduce((convertedData, _ref) => { | ||
@@ -38,3 +27,2 @@ let [key, value] = _ref; | ||
}; | ||
const requestContentType = (type, query) => { | ||
@@ -44,24 +32,17 @@ if (!query.data) { | ||
} | ||
if (type === 'json-patch') { | ||
return 'application/json-patch+json'; | ||
} | ||
if (resourceExpectsTextPlain(type, query)) { | ||
return 'text/plain'; | ||
} | ||
if (resourceExpectsMultipartFormData(type, query)) { | ||
return 'multipart/form-data'; | ||
} | ||
if (resourceExpectsXWwwFormUrlencoded(type, query)) { | ||
return 'application/x-www-form-urlencoded'; | ||
} | ||
return 'application/json'; | ||
}; | ||
exports.requestContentType = requestContentType; | ||
const requestHeadersForContentType = contentType => { | ||
@@ -78,3 +59,2 @@ /* | ||
} | ||
return { | ||
@@ -84,5 +64,3 @@ 'Content-Type': contentType | ||
}; | ||
exports.requestHeadersForContentType = requestHeadersForContentType; | ||
const requestBodyForContentType = (contentType, _ref2) => { | ||
@@ -92,23 +70,18 @@ let { | ||
} = _ref2; | ||
if (typeof data === 'undefined') { | ||
return undefined; | ||
} | ||
if (contentType === 'application/json' || contentType === 'application/json-patch+json') { | ||
return JSON.stringify(data); | ||
} | ||
if (contentType === 'multipart/form-data') { | ||
return convertData(data, new FormData()); | ||
} | ||
if (contentType === 'application/x-www-form-urlencoded') { | ||
return convertData(data, new URLSearchParams()); | ||
} // 'text/plain' | ||
} | ||
// 'text/plain' | ||
return data; | ||
}; | ||
exports.requestBodyForContentType = requestBodyForContentType; |
"use strict"; | ||
var _requestContentType = require("./requestContentType"); | ||
describe('requestContentType', () => { | ||
@@ -6,0 +5,0 @@ it('returns "application/json" for a normal resource', () => { |
@@ -7,3 +7,2 @@ "use strict"; | ||
exports.isUpdateInterpretation = exports.isReplyToMessageConversation = exports.isMetadataPackageInstallation = exports.isInterpretationCommentUpdate = exports.isExpressionDescriptionValidation = exports.isCreateInterpretation = exports.isCreateFeedbackMessage = exports.isCommentOnInterpretation = exports.isAddOrUpdateSystemOrUserSetting = exports.addOrUpdateConfigurationProperty = void 0; | ||
/* | ||
@@ -19,2 +18,3 @@ * Requests that expect a "text/plain" Content-Type have been collected by scanning | ||
*/ | ||
// POST to `messageConversations/${id}` (reply to a messagConversation) | ||
@@ -27,7 +27,6 @@ const isReplyToMessageConversation = (type, _ref) => { | ||
return type === 'create' && pattern.test(resource); | ||
}; // POST to 'messageConversations/feedback' (create a feedback message) | ||
}; | ||
// POST to 'messageConversations/feedback' (create a feedback message) | ||
exports.isReplyToMessageConversation = isReplyToMessageConversation; | ||
const isCreateFeedbackMessage = (type, _ref2) => { | ||
@@ -38,7 +37,6 @@ let { | ||
return type === 'create' && resource === 'messageConversations/feedback'; | ||
}; // POST `interpretations/${objectType}/${id}` (add an interpretation to a visualization) | ||
}; | ||
// POST `interpretations/${objectType}/${id}` (add an interpretation to a visualization) | ||
exports.isCreateFeedbackMessage = isCreateFeedbackMessage; | ||
const isCreateInterpretation = (type, _ref3) => { | ||
@@ -50,7 +48,6 @@ let { | ||
return type === 'create' && pattern.test(resource); | ||
}; // PUT to `interpretations/${id}` (update an interpretation) | ||
}; | ||
// PUT to `interpretations/${id}` (update an interpretation) | ||
exports.isCreateInterpretation = isCreateInterpretation; | ||
const isUpdateInterpretation = (type, _ref4) => { | ||
@@ -61,9 +58,6 @@ let { | ||
} = _ref4; | ||
if (type !== 'replace') { | ||
return false; | ||
} | ||
let resourcePattern; | ||
if (id) { | ||
@@ -74,10 +68,8 @@ resourcePattern = /^interpretations$/; | ||
} | ||
resourcePattern = /^interpretations\/[a-zA-Z0-9]{11}$/; | ||
return resourcePattern.test(resource); | ||
}; // POST to `interpretations/${id}/comments` (comment on an interpretation) | ||
}; | ||
// POST to `interpretations/${id}/comments` (comment on an interpretation) | ||
exports.isUpdateInterpretation = isUpdateInterpretation; | ||
const isCommentOnInterpretation = (type, _ref5) => { | ||
@@ -89,8 +81,7 @@ let { | ||
return type === 'create' && pattern.test(resource); | ||
}; // PUT to `interpretations/${interpretationId}/comments/${commentId}` | ||
}; | ||
// PUT to `interpretations/${interpretationId}/comments/${commentId}` | ||
// (update an interpretation comment) | ||
exports.isCommentOnInterpretation = isCommentOnInterpretation; | ||
const isInterpretationCommentUpdate = (type, _ref6) => { | ||
@@ -101,7 +92,5 @@ let { | ||
} = _ref6; | ||
if (type !== 'replace') { | ||
return false; | ||
} | ||
if (id) { | ||
@@ -113,11 +102,9 @@ const idPatternLong = /^[a-zA-Z0-9]{11}\/comments\/[a-zA-Z0-9]{11}$/; | ||
} | ||
const pattern = /^interpretations\/[a-zA-Z0-9]{11}\/comments\/[a-zA-Z0-9]{11}$/; | ||
return pattern.test(resource); | ||
}; // POST to `systemSettings/${settingKey}` or `userSettings/${settingKey}` | ||
}; | ||
// POST to `systemSettings/${settingKey}` or `userSettings/${settingKey}` | ||
// (add or update a single system or user setting) | ||
exports.isInterpretationCommentUpdate = isInterpretationCommentUpdate; | ||
const isAddOrUpdateSystemOrUserSetting = (type, _ref7) => { | ||
@@ -130,8 +117,7 @@ let { | ||
return type === 'create' && pattern.test(resource); | ||
}; // POST to `configuration/${configurationProperty}` | ||
}; | ||
// POST to `configuration/${configurationProperty}` | ||
// (add or update a single configuration property) | ||
exports.isAddOrUpdateSystemOrUserSetting = isAddOrUpdateSystemOrUserSetting; | ||
const addOrUpdateConfigurationProperty = (type, _ref8) => { | ||
@@ -145,7 +131,6 @@ let { | ||
return type === 'create' && !!match && match[2] !== 'corsWhitelist'; | ||
}; // POST to 'synchronization/metadataPull' (install a metadata package) | ||
}; | ||
// POST to 'synchronization/metadataPull' (install a metadata package) | ||
exports.addOrUpdateConfigurationProperty = addOrUpdateConfigurationProperty; | ||
const isMetadataPackageInstallation = (type, _ref9) => { | ||
@@ -156,7 +141,6 @@ let { | ||
return type === 'create' && resource === 'synchronization/metadataPull'; | ||
}; // POST to 'indicators/expression/description' or 'programIndicator/expression/description' (validate an expression) | ||
}; | ||
// POST to 'indicators/expression/description' or 'programIndicator/expression/description' (validate an expression) | ||
exports.isMetadataPackageInstallation = isMetadataPackageInstallation; | ||
const isExpressionDescriptionValidation = (type, _ref10) => { | ||
@@ -169,3 +153,2 @@ let { | ||
}; | ||
exports.isExpressionDescriptionValidation = isExpressionDescriptionValidation; |
"use strict"; | ||
var _textPlainMatchers = require("./textPlainMatchers"); | ||
describe('isReplyToMessageConversation', () => { | ||
@@ -6,0 +5,0 @@ it('retuns true for POST to `messageConversations/${id}`', () => { |
@@ -7,3 +7,2 @@ "use strict"; | ||
exports.isSvgConversion = void 0; | ||
// POST to convert an SVG file | ||
@@ -16,3 +15,2 @@ const isSvgConversion = (type, _ref) => { | ||
}; | ||
exports.isSvgConversion = isSvgConversion; |
"use strict"; | ||
var _xWwwFormUrlencodedMatchers = require("./xWwwFormUrlencodedMatchers"); | ||
describe('isSvgConversion', () => { | ||
@@ -6,0 +5,0 @@ it('returns true for a POST to "svg.png"', () => { |
@@ -7,7 +7,4 @@ "use strict"; | ||
exports.queryToResourcePath = void 0; | ||
var _path = require("./path"); | ||
var _validateQuery = require("./validateQuery"); | ||
const encodeQueryParameter = param => { | ||
@@ -17,21 +14,15 @@ if (Array.isArray(param)) { | ||
} | ||
if (typeof param === 'string') { | ||
return encodeURIComponent(param); | ||
} | ||
if (typeof param === 'number' || typeof param === 'boolean') { | ||
return String(param); | ||
} | ||
if (typeof param === 'object') { | ||
throw new Error('Object parameter mappings not yet implemented'); | ||
} | ||
throw new Error('Unknown parameter type'); | ||
}; | ||
const queryParametersMapToArray = params => Object.keys(params).reduce((out, key) => { | ||
const value = params[key]; | ||
if (key === 'filter' && Array.isArray(value)) { | ||
@@ -50,9 +41,7 @@ value.forEach(item => { | ||
} | ||
return out; | ||
}, []); | ||
const queryParametersToQueryString = params => { | ||
const expandedParams = queryParametersMapToArray(params); | ||
return expandedParams.map((_ref) => { | ||
return expandedParams.map(_ref => { | ||
let { | ||
@@ -65,26 +54,19 @@ key, | ||
}; | ||
const actionPrefix = 'action::'; | ||
const isAction = resource => resource.startsWith(actionPrefix); | ||
const makeActionPath = resource => (0, _path.joinPath)('dhis-web-commons', `${resource.substr(actionPrefix.length)}.action`); | ||
const skipApiVersion = (resource, config) => { | ||
if (resource === 'tracker' || resource.startsWith('tracker/')) { | ||
var _config$serverVersion, _config$serverVersion2; | ||
if (!((_config$serverVersion = config.serverVersion) !== null && _config$serverVersion !== void 0 && _config$serverVersion.minor) || ((_config$serverVersion2 = config.serverVersion) === null || _config$serverVersion2 === void 0 ? void 0 : _config$serverVersion2.minor) < 38) { | ||
return true; | ||
} | ||
} // The `/api/ping` endpoint is unversioned | ||
} | ||
// The `/api/ping` endpoint is unversioned | ||
if (resource === 'ping') { | ||
return true; | ||
} | ||
return false; | ||
}; | ||
const queryToResourcePath = (link, query, type) => { | ||
@@ -99,10 +81,7 @@ const { | ||
(0, _validateQuery.validateResourceQuery)(query, type); | ||
if (Object.keys(params).length) { | ||
return `${base}?${queryParametersToQueryString(params)}`; | ||
} | ||
return base; | ||
}; | ||
exports.queryToResourcePath = queryToResourcePath; |
"use strict"; | ||
var _RestAPILink = require("../RestAPILink"); | ||
var _queryToResourcePath = require("./queryToResourcePath"); | ||
const createLink = config => new _RestAPILink.RestAPILink(config); | ||
const defaultConfig = { | ||
@@ -166,3 +163,4 @@ basePath: '<base>', | ||
}; | ||
const v38config = { ...defaultConfig, | ||
const v38config = { | ||
...defaultConfig, | ||
serverVersion: { | ||
@@ -169,0 +167,0 @@ major: 2, |
@@ -7,28 +7,22 @@ "use strict"; | ||
exports.validateResourceQuery = void 0; | ||
var _metadataResources = require("./metadataResources"); | ||
const validatePagination = (query, warn) => { | ||
var _query$params, _query$params2; | ||
if (!_metadataResources.normativeMetadataResources.includes(query.resource)) { | ||
return true; | ||
} | ||
if (((_query$params = query.params) === null || _query$params === void 0 ? void 0 : _query$params.paging) === false || ((_query$params2 = query.params) === null || _query$params2 === void 0 ? void 0 : _query$params2.paging) === 'false') { | ||
warn('Data queries with paging=false are deprecated and should not be used!', query); | ||
return false; | ||
} // TODO: validate sub-resource pagination (i.e. fields=users~paging(1,50)[name] ) | ||
} | ||
// TODO: validate sub-resource pagination (i.e. fields=users~paging(1,50)[name] ) | ||
return true; | ||
}; | ||
const validateDeclarativeFields = (query, warn) => { | ||
var _query$params3; | ||
if (!_metadataResources.normativeMetadataResources.includes(query.resource)) { | ||
return true; | ||
} | ||
if (!((_query$params3 = query.params) !== null && _query$params3 !== void 0 && _query$params3.fields)) { | ||
@@ -39,5 +33,3 @@ warn('Data queries should always specify fields to return', query); | ||
var _fields; | ||
let fields = undefined; | ||
if (typeof query.params.fields === 'string') { | ||
@@ -48,3 +40,2 @@ fields = query.params.fields.split(',').map(field => field.trim()); | ||
} | ||
if ((_fields = fields) !== null && _fields !== void 0 && _fields.find(field => field.match(/(^\*$|^:.+)/))) { | ||
@@ -54,15 +45,12 @@ warn('Data queries should not use wildcard or dynamic field groups', query.params.fields, query); | ||
} | ||
} // TODO: validate sub-resource wildcard fields (i.e. fields=users[*]) | ||
} | ||
// TODO: validate sub-resource wildcard fields (i.e. fields=users[*]) | ||
return true; | ||
}; | ||
const validateResourceQuery = (query, type) => { | ||
let valid = true; | ||
if (process.env.NODE_ENV === 'development') { | ||
// Support build-time dead code elimination in production | ||
const warn = console.warn; | ||
if (type === 'read') { | ||
@@ -73,6 +61,4 @@ valid = validatePagination(query, warn) && valid; | ||
} | ||
return valid; | ||
}; | ||
exports.validateResourceQuery = validateResourceQuery; |
"use strict"; | ||
var _validateQuery = require("./validateQuery"); | ||
describe('validateQuery', () => { | ||
@@ -6,0 +5,0 @@ const originalConsoleWarn = console.warn; |
@@ -7,18 +7,10 @@ "use strict"; | ||
exports.CustomDataProvider = void 0; | ||
var _react = _interopRequireDefault(require("react")); | ||
var _reactQuery = require("react-query"); | ||
var _engine = require("../../engine"); | ||
var _links = require("../../links"); | ||
var _DataContext = require("../context/DataContext"); | ||
var _DataProvider = require("./DataProvider"); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
const CustomDataProvider = (_ref) => { | ||
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } | ||
const CustomDataProvider = _ref => { | ||
let { | ||
@@ -42,3 +34,2 @@ children, | ||
}; | ||
exports.CustomDataProvider = CustomDataProvider; |
@@ -7,6 +7,4 @@ "use strict"; | ||
exports.DataMutation = void 0; | ||
var _useDataMutation = require("../hooks/useDataMutation"); | ||
const DataMutation = (_ref) => { | ||
const DataMutation = _ref => { | ||
let { | ||
@@ -26,3 +24,2 @@ mutation, | ||
}; | ||
exports.DataMutation = DataMutation; |
@@ -7,19 +7,12 @@ "use strict"; | ||
exports.queryClientOptions = exports.DataProvider = void 0; | ||
var _appServiceConfig = require("@dhis2/app-service-config"); | ||
var _react = _interopRequireDefault(require("react")); | ||
var _reactQuery = require("react-query"); | ||
var _engine = require("../../engine"); | ||
var _links = require("../../links"); | ||
var _DataContext = require("../context/DataContext"); | ||
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } | ||
/* eslint-disable react/no-unused-prop-types */ | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
/* eslint-disable react/no-unused-prop-types */ | ||
const queryClientOptions = { | ||
const queryClientOptions = exports.queryClientOptions = { | ||
defaultOptions: { | ||
@@ -40,7 +33,6 @@ queries: { | ||
}; | ||
exports.queryClientOptions = queryClientOptions; | ||
const queryClient = new _reactQuery.QueryClient(queryClientOptions); | ||
const DataProvider = props => { | ||
const config = { ...(0, _appServiceConfig.useConfig)(), | ||
const config = { | ||
...(0, _appServiceConfig.useConfig)(), | ||
...props | ||
@@ -59,3 +51,2 @@ }; | ||
}; | ||
exports.DataProvider = DataProvider; |
"use strict"; | ||
var _react = require("@testing-library/react"); | ||
var _react2 = _interopRequireDefault(require("react")); | ||
var _engine = require("../../engine"); | ||
var _links = require("../../links"); | ||
var _DataContext = require("../context/DataContext"); | ||
var _DataProvider = require("./DataProvider"); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } | ||
describe('DataProvider', () => { | ||
it('Should pass a new engine and RestAPILink to consumers', () => { | ||
const renderFunction = jest.fn(); | ||
(0, _react.render)( /*#__PURE__*/_react2.default.createElement(_DataProvider.DataProvider, { | ||
(0, _react.render)(/*#__PURE__*/_react2.default.createElement(_DataProvider.DataProvider, { | ||
baseUrl: "test", | ||
@@ -22,0 +15,0 @@ apiVersion: 42 |
@@ -7,6 +7,4 @@ "use strict"; | ||
exports.DataQuery = void 0; | ||
var _useDataQuery = require("../hooks/useDataQuery"); | ||
const DataQuery = (_ref) => { | ||
const DataQuery = _ref => { | ||
let { | ||
@@ -28,3 +26,2 @@ query, | ||
}; | ||
exports.DataQuery = DataQuery; |
@@ -7,11 +7,5 @@ "use strict"; | ||
exports.DataContext = void 0; | ||
var _react = _interopRequireDefault(require("react")); | ||
var _defaultContext = require("./defaultContext"); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
const DataContext = /*#__PURE__*/_react.default.createContext(_defaultContext.defaultContext); | ||
exports.DataContext = DataContext; | ||
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } | ||
const DataContext = exports.DataContext = /*#__PURE__*/_react.default.createContext(_defaultContext.defaultContext); |
@@ -7,13 +7,9 @@ "use strict"; | ||
exports.defaultContext = void 0; | ||
var _engine = require("../../engine"); | ||
var _links = require("../../links"); | ||
const errorMessage = 'DHIS2 data context must be initialized, please ensure that you include a <DataProvider> in your application'; | ||
const link = new _links.ErrorLink(errorMessage); | ||
const engine = new _engine.DataEngine(link); | ||
const defaultContext = { | ||
const defaultContext = exports.defaultContext = { | ||
engine | ||
}; | ||
exports.defaultContext = defaultContext; | ||
}; |
"use strict"; | ||
var _defaultContext = require("./defaultContext"); | ||
describe('defaultContext', () => { | ||
@@ -6,0 +5,0 @@ const originalError = console.error; |
@@ -7,5 +7,3 @@ "use strict"; | ||
exports.mergeAndCompareVariables = void 0; | ||
var _stableVariablesHash = require("./stableVariablesHash"); | ||
const mergeAndCompareVariables = (previousVariables, newVariables, previousHash) => { | ||
@@ -18,7 +16,8 @@ if (!newVariables) { | ||
}; | ||
} // Use cached hash if it exists | ||
} | ||
// Use cached hash if it exists | ||
const currentHash = previousHash || (0, _stableVariablesHash.stableVariablesHash)(previousVariables); | ||
const mergedVariables = { ...previousVariables, | ||
const mergedVariables = { | ||
...previousVariables, | ||
...newVariables | ||
@@ -34,3 +33,2 @@ }; | ||
}; | ||
exports.mergeAndCompareVariables = mergeAndCompareVariables; |
"use strict"; | ||
var _mergeAndCompareVariables = require("./mergeAndCompareVariables"); | ||
var _stableVariablesHash = require("./stableVariablesHash"); | ||
jest.mock('./stableVariablesHash', () => ({ | ||
@@ -48,3 +46,4 @@ stableVariablesHash: object => JSON.stringify(object) | ||
}; | ||
const expectedMergedVariables = { ...testVariables, | ||
const expectedMergedVariables = { | ||
...testVariables, | ||
...newVariables | ||
@@ -51,0 +50,0 @@ }; |
@@ -8,35 +8,33 @@ "use strict"; | ||
exports.stableVariablesHash = stableVariablesHash; | ||
function hasObjectPrototype(o) { | ||
return Object.prototype.toString.call(o) === '[object Object]'; | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
} | ||
// eslint-disable-next-line @typescript-eslint/ban-types | ||
function isPlainObject(o) { | ||
if (!hasObjectPrototype(o)) { | ||
return false; | ||
} // If has modified constructor | ||
} | ||
// If has modified constructor | ||
const ctor = o.constructor; | ||
if (typeof ctor === 'undefined') { | ||
return true; | ||
} // If has modified prototype | ||
} | ||
// If has modified prototype | ||
const prot = ctor.prototype; | ||
if (!hasObjectPrototype(prot)) { | ||
return false; | ||
} // If constructor does not have an Object-specific method | ||
} | ||
// If constructor does not have an Object-specific method | ||
if (!Object.prototype.hasOwnProperty.call(prot, 'isPrototypeOf')) { | ||
return false; | ||
} // Most likely a plain Object | ||
} | ||
// Most likely a plain Object | ||
return true; | ||
} | ||
/** | ||
@@ -46,6 +44,4 @@ * Hashes the value into a stable hash. | ||
function stableVariablesHash(value) { | ||
let hash; | ||
try { | ||
@@ -59,4 +55,3 @@ hash = JSON.stringify(value, (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => { | ||
} | ||
return hash; | ||
} |
"use strict"; | ||
var _stableVariablesHash = require("./stableVariablesHash"); | ||
describe('stableVariablesHash', () => { | ||
@@ -6,0 +5,0 @@ it('sorts objects before hashing', () => { |
@@ -7,7 +7,4 @@ "use strict"; | ||
exports.useDataEngine = void 0; | ||
var _react = require("react"); | ||
var _DataContext = require("../context/DataContext"); | ||
const useDataEngine = () => { | ||
@@ -17,3 +14,2 @@ const context = (0, _react.useContext)(_DataContext.DataContext); | ||
}; | ||
exports.useDataEngine = useDataEngine; |
@@ -7,13 +7,7 @@ "use strict"; | ||
exports.useDataMutation = void 0; | ||
var _react = require("react"); | ||
var _useDataEngine = require("./useDataEngine"); | ||
var _useQueryExecutor = require("./useQueryExecutor"); | ||
var _useStaticInput = require("./useStaticInput"); | ||
const empty = {}; | ||
const useDataMutation = function (mutation) { | ||
@@ -54,3 +48,2 @@ let { | ||
}; | ||
exports.useDataMutation = useDataMutation; |
"use strict"; | ||
var _reactHooks = require("@testing-library/react-hooks"); | ||
var _react = require("@testing-library/react"); | ||
var React = _interopRequireWildcard(require("react")); | ||
var _CustomDataProvider = require("../components/CustomDataProvider"); | ||
var _useDataEngine = require("./useDataEngine"); | ||
var _useDataMutation = require("./useDataMutation"); | ||
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } | ||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } | ||
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } | ||
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } | ||
describe('useDataMutation', () => { | ||
@@ -29,4 +22,3 @@ it('should render without failing', async () => { | ||
}; | ||
const wrapper = (_ref) => { | ||
const wrapper = _ref => { | ||
let { | ||
@@ -39,7 +31,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataMutation.useDataMutation)(mutation), { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataMutation.useDataMutation)(mutation), { | ||
wrapper | ||
@@ -52,6 +42,6 @@ }); | ||
}); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
mutate(); | ||
}); | ||
await waitFor(() => { | ||
await (0, _react.waitFor)(() => { | ||
const [, duringMutation] = result.current; | ||
@@ -63,3 +53,3 @@ expect(duringMutation).toMatchObject({ | ||
}); | ||
await waitFor(() => { | ||
await (0, _react.waitFor)(() => { | ||
const [, afterMutation] = result.current; | ||
@@ -84,4 +74,3 @@ expect(afterMutation).toMatchObject({ | ||
}; | ||
const wrapper = (_ref2) => { | ||
const wrapper = _ref2 => { | ||
let { | ||
@@ -94,7 +83,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataMutation.useDataMutation)(mutation, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataMutation.useDataMutation)(mutation, { | ||
lazy: false | ||
@@ -109,3 +96,3 @@ }), { | ||
}); | ||
await waitFor(() => { | ||
await (0, _react.waitFor)(() => { | ||
const [, afterMutation] = result.current; | ||
@@ -131,4 +118,3 @@ expect(afterMutation).toMatchObject({ | ||
}; | ||
const wrapper = (_ref3) => { | ||
const wrapper = _ref3 => { | ||
let { | ||
@@ -141,7 +127,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataMutation.useDataMutation)(mutation, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataMutation.useDataMutation)(mutation, { | ||
onComplete | ||
@@ -153,6 +137,6 @@ }), { | ||
const [mutate] = result.current; | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
mutate(); | ||
}); | ||
await waitFor(() => { | ||
await (0, _react.waitFor)(() => { | ||
const [, state] = result.current; | ||
@@ -183,4 +167,3 @@ expect(state).toMatchObject({ | ||
}; | ||
const wrapper = (_ref4) => { | ||
const wrapper = _ref4 => { | ||
let { | ||
@@ -193,7 +176,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataMutation.useDataMutation)(mutation, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataMutation.useDataMutation)(mutation, { | ||
onError | ||
@@ -205,6 +186,6 @@ }), { | ||
const [mutate] = result.current; | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
mutate(); | ||
}); | ||
await waitFor(() => { | ||
await (0, _react.waitFor)(() => { | ||
const [, state] = result.current; | ||
@@ -224,3 +205,3 @@ expect(state).toMatchObject({ | ||
resource: 'answer', | ||
id: (_ref5) => { | ||
id: _ref5 => { | ||
let { | ||
@@ -239,4 +220,3 @@ id | ||
}; | ||
const wrapper = (_ref6) => { | ||
const wrapper = _ref6 => { | ||
let { | ||
@@ -249,7 +229,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataMutation.useDataMutation)(mutation, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataMutation.useDataMutation)(mutation, { | ||
lazy: false, | ||
@@ -262,3 +240,3 @@ variables: { | ||
}); | ||
await waitFor(() => { | ||
await (0, _react.waitFor)(() => { | ||
expect(answerSpy).toHaveBeenLastCalledWith(expect.any(String), expect.objectContaining({ | ||
@@ -269,3 +247,3 @@ id: '1' | ||
const [mutate] = result.current; | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
mutate({ | ||
@@ -275,3 +253,3 @@ id: '2' | ||
}); | ||
await waitFor(() => { | ||
await (0, _react.waitFor)(() => { | ||
expect(answerSpy).toHaveBeenLastCalledWith(expect.any(String), expect.objectContaining({ | ||
@@ -290,4 +268,3 @@ id: '2' | ||
}; | ||
const wrapper = (_ref7) => { | ||
const wrapper = _ref7 => { | ||
let { | ||
@@ -300,9 +277,9 @@ children | ||
}; | ||
const engineHook = (0, _reactHooks.renderHook)(() => (0, _useDataEngine.useDataEngine)(), { | ||
const engineHook = (0, _react.renderHook)(() => (0, _useDataEngine.useDataEngine)(), { | ||
wrapper | ||
}); | ||
const mutationHook = (0, _reactHooks.renderHook)(() => (0, _useDataMutation.useDataMutation)(mutation), { | ||
const mutationHook = (0, _react.renderHook)(() => (0, _useDataMutation.useDataMutation)(mutation), { | ||
wrapper | ||
}); | ||
/** | ||
@@ -312,3 +289,2 @@ * Ideally we'd check referential equality here with .toBe, but since | ||
*/ | ||
expect(mutationHook.result.current[1].engine).toStrictEqual(engineHook.result.current); | ||
@@ -327,4 +303,3 @@ }); | ||
}; | ||
const wrapper = (_ref8) => { | ||
const wrapper = _ref8 => { | ||
let { | ||
@@ -337,10 +312,9 @@ children | ||
}; | ||
const { | ||
result | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataMutation.useDataMutation)(mutation), { | ||
} = (0, _react.renderHook)(() => (0, _useDataMutation.useDataMutation)(mutation), { | ||
wrapper | ||
}); | ||
const [firstMutate] = result.current; | ||
await (0, _reactHooks.act)(async () => { | ||
await (0, _react.act)(async () => { | ||
await firstMutate({ | ||
@@ -368,4 +342,3 @@ variable: 'variable' | ||
}; | ||
const wrapper = (_ref9) => { | ||
const wrapper = _ref9 => { | ||
let { | ||
@@ -378,7 +351,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataMutation.useDataMutation)(mutation), { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataMutation.useDataMutation)(mutation), { | ||
wrapper | ||
@@ -388,6 +359,6 @@ }); | ||
const [mutate] = result.current; | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
mutatePromise = mutate(); | ||
}); | ||
await waitFor(() => { | ||
await (0, _react.waitFor)(() => { | ||
const [, state] = result.current; | ||
@@ -394,0 +365,0 @@ expect(state).toMatchObject({ |
@@ -7,13 +7,7 @@ "use strict"; | ||
exports.useDataQuery = void 0; | ||
var _react = require("react"); | ||
var _reactQuery = require("react-query"); | ||
var _mergeAndCompareVariables = require("./mergeAndCompareVariables"); | ||
var _useDataEngine = require("./useDataEngine"); | ||
var _useStaticInput = require("./useStaticInput"); | ||
const noop = () => { | ||
@@ -26,3 +20,2 @@ /** | ||
}; | ||
(0, _reactQuery.setLogger)({ | ||
@@ -33,3 +26,2 @@ log: noop, | ||
}); | ||
const useDataQuery = function (query) { | ||
@@ -53,2 +45,3 @@ let { | ||
}); | ||
/** | ||
@@ -63,2 +56,3 @@ * Display current query state and refetch count in React DevTools | ||
}, debugValue => JSON.stringify(debugValue)); | ||
/** | ||
@@ -70,6 +64,4 @@ * User callbacks and refetch handling | ||
var _queryState$current$r, _queryState$current; | ||
(_queryState$current$r = (_queryState$current = queryState.current).refetchCallback) === null || _queryState$current$r === void 0 ? void 0 : _queryState$current$r.call(_queryState$current, data); | ||
queryState.current.refetchCallback = undefined; | ||
if (userOnSuccess) { | ||
@@ -79,7 +71,5 @@ userOnSuccess(data); | ||
}; | ||
const onError = error => { | ||
// If we'd want to reject on errors we'd call the cb with the error here | ||
queryState.current.refetchCallback = undefined; | ||
if (userOnError) { | ||
@@ -89,2 +79,3 @@ userOnError(error); | ||
}; | ||
/** | ||
@@ -94,10 +85,7 @@ * Setting up react-query | ||
const engine = (0, _useDataEngine.useDataEngine)(); | ||
const queryKey = [staticQuery, queryState.current.variables]; | ||
const queryFn = () => engine.query(staticQuery, { | ||
variables: queryState.current.variables | ||
}); | ||
const { | ||
@@ -115,2 +103,3 @@ isIdle, | ||
}); | ||
/** | ||
@@ -131,2 +120,3 @@ * Refetch allows a user to update the variables or just | ||
} = (0, _mergeAndCompareVariables.mergeAndCompareVariables)(queryState.current.variables, newVariables, queryState.current.variablesHash); | ||
/** | ||
@@ -136,3 +126,2 @@ * If there are no updates that will trigger an automatic refetch | ||
*/ | ||
if (queryState.current.enabled && identical) { | ||
@@ -142,3 +131,3 @@ return queryRefetch({ | ||
throwOnError: false | ||
}).then((_ref) => { | ||
}).then(_ref => { | ||
let { | ||
@@ -150,7 +139,7 @@ data | ||
} | ||
queryState.current.variables = mergedVariables; | ||
queryState.current.variablesHash = mergedVariablesHash; | ||
queryState.current.enabled = true; // This promise does not currently reject on errors | ||
queryState.current.enabled = true; | ||
// This promise does not currently reject on errors | ||
const refetchPromise = new Promise(resolve => { | ||
@@ -160,7 +149,9 @@ queryState.current.refetchCallback = data => { | ||
}; | ||
}); // Trigger a react-query refetch by incrementing variablesUpdateCount state | ||
}); | ||
// Trigger a react-query refetch by incrementing variablesUpdateCount state | ||
setVariablesUpdateCount(prevCount => prevCount + 1); | ||
return refetchPromise; | ||
}, [queryRefetch]); | ||
/** | ||
@@ -170,3 +161,2 @@ * react-query returns null or an error, but we return undefined | ||
*/ | ||
const ourError = error || undefined; | ||
@@ -184,3 +174,2 @@ return { | ||
}; | ||
exports.useDataQuery = useDataQuery; |
"use strict"; | ||
var _reactHooks = require("@testing-library/react-hooks"); | ||
var _react = require("@testing-library/react"); | ||
var React = _interopRequireWildcard(require("react")); | ||
var _CustomDataProvider = require("../components/CustomDataProvider"); | ||
var _useDataQuery = require("./useDataQuery"); | ||
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } | ||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } | ||
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } | ||
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } | ||
describe('useDataQuery', () => { | ||
@@ -26,4 +20,3 @@ describe('parameters: onComplete', () => { | ||
}; | ||
const wrapper = (_ref) => { | ||
const wrapper = _ref => { | ||
let { | ||
@@ -36,9 +29,7 @@ children | ||
}; | ||
const onComplete = jest.fn(); | ||
const onError = jest.fn(); | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
lazy: false, | ||
@@ -54,11 +45,12 @@ onComplete, | ||
}); | ||
await waitForNextUpdate(); | ||
expect(onComplete).toHaveBeenCalledWith({ | ||
x: 42 | ||
}); | ||
expect(onError).not.toHaveBeenCalled(); | ||
expect(result.current).toMatchObject({ | ||
data: { | ||
await (0, _react.waitFor)(() => { | ||
expect(onComplete).toHaveBeenCalledWith({ | ||
x: 42 | ||
} | ||
}); | ||
expect(onError).not.toHaveBeenCalled(); | ||
expect(result.current).toMatchObject({ | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
@@ -80,4 +72,3 @@ }); | ||
}; | ||
const wrapper = (_ref2) => { | ||
const wrapper = _ref2 => { | ||
let { | ||
@@ -90,9 +81,7 @@ children | ||
}; | ||
const onComplete = jest.fn(); | ||
const onError = jest.fn(); | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
onError, | ||
@@ -107,7 +96,8 @@ onComplete | ||
}); | ||
await waitForNextUpdate(); | ||
expect(onError).toHaveBeenCalledWith(expectedError); | ||
expect(onComplete).not.toHaveBeenCalled(); | ||
expect(result.current).toMatchObject({ | ||
error: expectedError | ||
await (0, _react.waitFor)(() => { | ||
expect(onError).toHaveBeenCalledWith(expectedError); | ||
expect(onComplete).not.toHaveBeenCalled(); | ||
expect(result.current).toMatchObject({ | ||
error: expectedError | ||
}); | ||
}); | ||
@@ -125,3 +115,3 @@ }); | ||
resource: 'answer', | ||
id: (_ref3) => { | ||
id: _ref3 => { | ||
let { | ||
@@ -138,7 +128,5 @@ id | ||
} = _ref4; | ||
switch (id) { | ||
case one: | ||
return Promise.resolve(resultOne); | ||
case two: | ||
@@ -151,4 +139,3 @@ return Promise.resolve(resultTwo); | ||
}; | ||
const wrapper = (_ref5) => { | ||
const wrapper = _ref5 => { | ||
let { | ||
@@ -161,3 +148,2 @@ children | ||
}; | ||
const initialProps = { | ||
@@ -173,5 +159,4 @@ query, | ||
result, | ||
waitForNextUpdate, | ||
rerender | ||
} = (0, _reactHooks.renderHook)(props => (0, _useDataQuery.useDataQuery)(props.query, props.options), { | ||
} = (0, _react.renderHook)(props => (0, _useDataQuery.useDataQuery)(props.query, props.options), { | ||
wrapper, | ||
@@ -185,9 +170,10 @@ initialProps | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
data: { | ||
x: resultOne | ||
} | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
data: { | ||
x: resultOne | ||
} | ||
}); | ||
}); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
const newProps = { | ||
@@ -222,4 +208,3 @@ query, | ||
}; | ||
const wrapper = (_ref6) => { | ||
const wrapper = _ref6 => { | ||
let { | ||
@@ -232,7 +217,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query), { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query), { | ||
wrapper | ||
@@ -244,10 +227,11 @@ }); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(mockSpy).toHaveBeenCalledTimes(1); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
await (0, _react.waitFor)(() => { | ||
expect(mockSpy).toHaveBeenCalledTimes(1); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
@@ -276,4 +260,3 @@ }); | ||
}; | ||
const wrapper = (_ref7) => { | ||
const wrapper = _ref7 => { | ||
let { | ||
@@ -287,7 +270,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query), { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query), { | ||
wrapper | ||
@@ -300,12 +281,13 @@ }); | ||
}); | ||
await waitForNextUpdate(); // Now the cache will contain a value for 'answer' without variables | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
await (0, _react.waitFor)(() => { | ||
// Now the cache will contain a value for 'answer' without variables | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
// Add a variable to the request to ensure a different cache key | ||
@@ -320,11 +302,12 @@ result.current.refetch({ | ||
}); | ||
await waitForNextUpdate(); // Now the cache will contain a value for 'answer' with and without variables | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
data: { | ||
x: 43 | ||
} | ||
await (0, _react.waitFor)(() => { | ||
// Now the cache will contain a value for 'answer' with and without variables | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
data: { | ||
x: 43 | ||
} | ||
}); | ||
}); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
// Request the resource without variables again | ||
@@ -334,4 +317,5 @@ result.current.refetch({ | ||
}); | ||
}); // This should return the resource from the cache without fetching | ||
}); | ||
// This should return the resource from the cache without fetching | ||
expect(mockSpy).toHaveBeenCalledTimes(2); | ||
@@ -358,4 +342,3 @@ expect(result.current).toMatchObject({ | ||
}; | ||
const wrapper = (_ref8) => { | ||
const wrapper = _ref8 => { | ||
let { | ||
@@ -368,7 +351,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => { | ||
result | ||
} = (0, _react.renderHook)(() => { | ||
const one = (0, _useDataQuery.useDataQuery)(query); | ||
@@ -387,12 +368,13 @@ const two = (0, _useDataQuery.useDataQuery)(query); | ||
expect(result.current).toMatchObject([loading, loading, loading]); | ||
await waitForNextUpdate(); | ||
const done = { | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}; | ||
expect(mockSpy).toHaveBeenCalledTimes(1); | ||
expect(result.current).toMatchObject([done, done, done]); | ||
await (0, _react.waitFor)(() => { | ||
const done = { | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}; | ||
expect(mockSpy).toHaveBeenCalledTimes(1); | ||
expect(result.current).toMatchObject([done, done, done]); | ||
}); | ||
}); | ||
@@ -410,4 +392,3 @@ }); | ||
}; | ||
const wrapper = (_ref9) => { | ||
const wrapper = _ref9 => { | ||
let { | ||
@@ -420,7 +401,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query), { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query), { | ||
wrapper | ||
@@ -432,9 +411,10 @@ }); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
@@ -455,4 +435,3 @@ }); | ||
}; | ||
const wrapper = (_ref10) => { | ||
const wrapper = _ref10 => { | ||
let { | ||
@@ -465,7 +444,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query), { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query), { | ||
wrapper | ||
@@ -477,10 +454,11 @@ }); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42, | ||
y: 24 | ||
} | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42, | ||
y: 24 | ||
} | ||
}); | ||
}); | ||
@@ -502,4 +480,3 @@ }); | ||
}; | ||
const wrapper = (_ref11) => { | ||
const wrapper = _ref11 => { | ||
let { | ||
@@ -512,7 +489,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query), { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query), { | ||
wrapper | ||
@@ -524,7 +499,8 @@ }); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
error: expectedError | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
error: expectedError | ||
}); | ||
}); | ||
@@ -548,4 +524,3 @@ }); | ||
}; | ||
const wrapper = (_ref12) => { | ||
const wrapper = _ref12 => { | ||
let { | ||
@@ -558,7 +533,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query), { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query), { | ||
wrapper | ||
@@ -570,7 +543,8 @@ }); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
error: expectedError | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
error: expectedError | ||
}); | ||
}); | ||
@@ -594,4 +568,3 @@ }); | ||
}; | ||
const wrapper = (_ref13) => { | ||
const wrapper = _ref13 => { | ||
let { | ||
@@ -604,7 +577,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
lazy: true | ||
@@ -616,6 +587,6 @@ }), { | ||
const initialRefetch = result.current.refetch; | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
initialRefetch(); | ||
}); | ||
await waitFor(() => { | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
@@ -630,6 +601,6 @@ loading: false, | ||
expect(spy).toHaveBeenCalledTimes(1); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
initialRefetch(); | ||
}); | ||
await waitFor(() => { | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
@@ -651,3 +622,2 @@ loading: false, | ||
} | ||
return 0; | ||
@@ -661,3 +631,3 @@ }); | ||
resource: 'answer', | ||
id: (_ref14) => { | ||
id: _ref14 => { | ||
let { | ||
@@ -670,4 +640,3 @@ id | ||
}; | ||
const wrapper = (_ref15) => { | ||
const wrapper = _ref15 => { | ||
let { | ||
@@ -680,7 +649,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
lazy: true | ||
@@ -691,3 +658,3 @@ }), { | ||
expect(spy).not.toHaveBeenCalled(); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
result.current.refetch({ | ||
@@ -697,3 +664,3 @@ id: '1' | ||
}); | ||
await waitFor(() => { | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
@@ -714,3 +681,2 @@ loading: false, | ||
} | ||
return 0; | ||
@@ -724,3 +690,3 @@ }); | ||
resource: 'answer', | ||
id: (_ref16) => { | ||
id: _ref16 => { | ||
let { | ||
@@ -733,4 +699,3 @@ id | ||
}; | ||
const wrapper = (_ref17) => { | ||
const wrapper = _ref17 => { | ||
let { | ||
@@ -743,7 +708,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
lazy: true, | ||
@@ -757,3 +720,3 @@ variables: { | ||
expect(spy).not.toHaveBeenCalled(); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
result.current.refetch({ | ||
@@ -763,3 +726,3 @@ id: '1' | ||
}); | ||
await waitFor(() => { | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
@@ -784,4 +747,3 @@ loading: false, | ||
}; | ||
const wrapper = (_ref18) => { | ||
const wrapper = _ref18 => { | ||
let { | ||
@@ -794,14 +756,15 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate, | ||
rerender | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query), { | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query), { | ||
wrapper | ||
}); | ||
const firstRefetch = result.current.refetch; | ||
await waitForNextUpdate(); | ||
(0, _reactHooks.act)(() => { | ||
// await waitFor(() => {}) | ||
(0, _react.act)(() => { | ||
result.current.refetch(); | ||
/** | ||
@@ -812,7 +775,7 @@ * FIXME: https://github.com/tannerlinsley/react-query/issues/2481 | ||
*/ | ||
rerender(); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current.refetch).toBe(firstRefetch); | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current.refetch).toBe(firstRefetch); | ||
}); | ||
}); | ||
@@ -830,4 +793,3 @@ it('Should return stale data and set loading to true on refetch', async () => { | ||
}; | ||
const wrapper = (_ref19) => { | ||
const wrapper = _ref19 => { | ||
let { | ||
@@ -840,8 +802,6 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate, | ||
rerender | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query), { | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query), { | ||
wrapper | ||
@@ -854,12 +814,14 @@ }); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
result.current.refetch(); | ||
/** | ||
@@ -870,3 +832,2 @@ * FIXME: https://github.com/tannerlinsley/react-query/issues/2481 | ||
*/ | ||
rerender(); | ||
@@ -883,11 +844,12 @@ }); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(mockSpy).toHaveBeenCalledTimes(2); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
fetching: false, | ||
called: true, | ||
data: { | ||
x: 43 | ||
} | ||
await (0, _react.waitFor)(() => { | ||
expect(mockSpy).toHaveBeenCalledTimes(2); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
fetching: false, | ||
called: true, | ||
data: { | ||
x: 43 | ||
} | ||
}); | ||
}); | ||
@@ -905,4 +867,3 @@ }); | ||
}; | ||
const wrapper = (_ref20) => { | ||
const wrapper = _ref20 => { | ||
let { | ||
@@ -915,7 +876,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
lazy: true | ||
@@ -930,3 +889,3 @@ }), { | ||
}); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
result.current.refetch(); | ||
@@ -939,9 +898,10 @@ }); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
@@ -958,4 +918,3 @@ }); | ||
}; | ||
const wrapper = (_ref21) => { | ||
const wrapper = _ref21 => { | ||
let { | ||
@@ -968,9 +927,7 @@ children | ||
}; | ||
const onComplete = jest.fn(); | ||
const onError = jest.fn(); | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
lazy: true, | ||
@@ -982,17 +939,18 @@ onComplete, | ||
}); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
result.current.refetch(); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
expect(onComplete).toHaveBeenCalledWith({ | ||
x: 42 | ||
} | ||
}); | ||
expect(onError).not.toHaveBeenCalled(); | ||
}); | ||
expect(onComplete).toHaveBeenCalledWith({ | ||
x: 42 | ||
}); | ||
expect(onError).not.toHaveBeenCalled(); | ||
}); | ||
@@ -1011,4 +969,3 @@ it('Should call onError after a failed refetch', async () => { | ||
}; | ||
const wrapper = (_ref22) => { | ||
const wrapper = _ref22 => { | ||
let { | ||
@@ -1021,9 +978,7 @@ children | ||
}; | ||
const onComplete = jest.fn(); | ||
const onError = jest.fn(); | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
lazy: true, | ||
@@ -1035,10 +990,11 @@ onComplete, | ||
}); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
result.current.refetch(); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(onError).toHaveBeenCalledWith(expectedError); | ||
expect(onComplete).not.toHaveBeenCalled(); | ||
expect(result.current).toMatchObject({ | ||
error: expectedError | ||
await (0, _react.waitFor)(() => { | ||
expect(onError).toHaveBeenCalledWith(expectedError); | ||
expect(onComplete).not.toHaveBeenCalled(); | ||
expect(result.current).toMatchObject({ | ||
error: expectedError | ||
}); | ||
}); | ||
@@ -1055,3 +1011,3 @@ }); | ||
resource: 'answer', | ||
params: (_ref23) => { | ||
params: _ref23 => { | ||
let { | ||
@@ -1074,4 +1030,3 @@ one, | ||
}; | ||
const wrapper = (_ref24) => { | ||
const wrapper = _ref24 => { | ||
let { | ||
@@ -1084,7 +1039,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
variables | ||
@@ -1094,22 +1047,24 @@ }), { | ||
}); | ||
await waitForNextUpdate(); | ||
expect(spy).toHaveBeenCalledTimes(1); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
await (0, _react.waitFor)(() => { | ||
expect(spy).toHaveBeenCalledTimes(1); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
result.current.refetch(variables); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(spy).toHaveBeenCalledTimes(2); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
await (0, _react.waitFor)(() => { | ||
expect(spy).toHaveBeenCalledTimes(2); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
@@ -1126,4 +1081,3 @@ }); | ||
}; | ||
const wrapper = (_ref25) => { | ||
const wrapper = _ref25 => { | ||
let { | ||
@@ -1136,7 +1090,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
lazy: true | ||
@@ -1147,16 +1099,17 @@ }), { | ||
let ourPromise; | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
// This refetch will trigger our own refetch logic as the query is lazy | ||
ourPromise = result.current.refetch(); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(ourPromise).resolves.toEqual({ | ||
x: 42 | ||
}); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
await (0, _react.waitFor)(() => { | ||
expect(ourPromise).resolves.toEqual({ | ||
x: 42 | ||
} | ||
}); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
@@ -1173,4 +1126,3 @@ }); | ||
}; | ||
const wrapper = (_ref26) => { | ||
const wrapper = _ref26 => { | ||
let { | ||
@@ -1183,7 +1135,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
lazy: false | ||
@@ -1194,16 +1144,17 @@ }), { | ||
let reactQueryPromise; | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
// This refetch will trigger react query's refetch logic as the query is not lazy | ||
reactQueryPromise = result.current.refetch(); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(reactQueryPromise).resolves.toEqual({ | ||
x: 42 | ||
}); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
await (0, _react.waitFor)(() => { | ||
expect(reactQueryPromise).resolves.toEqual({ | ||
x: 42 | ||
} | ||
}); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
@@ -1223,4 +1174,3 @@ }); | ||
}; | ||
const wrapper = (_ref27) => { | ||
const wrapper = _ref27 => { | ||
let { | ||
@@ -1233,7 +1183,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
lazy: true | ||
@@ -1244,10 +1192,11 @@ }), { | ||
let ourPromise; | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
// This refetch will trigger our own refetch logic as the query is lazy | ||
ourPromise = result.current.refetch(); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(ourPromise).resolves.toBeUndefined(); | ||
expect(result.current).toMatchObject({ | ||
error: expectedError | ||
await (0, _react.waitFor)(() => { | ||
expect(ourPromise).resolves.toBeUndefined(); | ||
expect(result.current).toMatchObject({ | ||
error: expectedError | ||
}); | ||
}); | ||
@@ -1267,4 +1216,3 @@ }); | ||
}; | ||
const wrapper = (_ref28) => { | ||
const wrapper = _ref28 => { | ||
let { | ||
@@ -1277,7 +1225,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
lazy: false | ||
@@ -1288,10 +1234,11 @@ }), { | ||
let reactQueryPromise; | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
// This refetch will trigger react query's refetch logic as the query is not lazy | ||
reactQueryPromise = result.current.refetch(); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(reactQueryPromise).resolves.toBeUndefined(); | ||
expect(result.current).toMatchObject({ | ||
error: expectedError | ||
await (0, _react.waitFor)(() => { | ||
expect(reactQueryPromise).resolves.toBeUndefined(); | ||
expect(result.current).toMatchObject({ | ||
error: expectedError | ||
}); | ||
}); | ||
@@ -1307,3 +1254,3 @@ }); | ||
resource: 'answer', | ||
id: (_ref29) => { | ||
id: _ref29 => { | ||
let { | ||
@@ -1320,7 +1267,5 @@ id | ||
} = _ref30; | ||
switch (id) { | ||
case one: | ||
return Promise.resolve(resultOne); | ||
case two: | ||
@@ -1333,4 +1278,3 @@ return Promise.resolve(resultTwo); | ||
}; | ||
const wrapper = (_ref31) => { | ||
const wrapper = _ref31 => { | ||
let { | ||
@@ -1343,3 +1287,2 @@ children | ||
}; | ||
const initialProps = { | ||
@@ -1354,15 +1297,15 @@ query, | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(props => (0, _useDataQuery.useDataQuery)(props.query, props.options), { | ||
result | ||
} = (0, _react.renderHook)(props => (0, _useDataQuery.useDataQuery)(props.query, props.options), { | ||
wrapper, | ||
initialProps | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
data: { | ||
x: resultOne | ||
} | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
data: { | ||
x: resultOne | ||
} | ||
}); | ||
}); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
result.current.refetch({ | ||
@@ -1372,8 +1315,9 @@ id: two | ||
}); | ||
await waitForNextUpdate(); | ||
expect(mockSpy).toHaveBeenCalledTimes(2); | ||
expect(result.current).toMatchObject({ | ||
data: { | ||
x: resultTwo | ||
} | ||
await (0, _react.waitFor)(() => { | ||
expect(mockSpy).toHaveBeenCalledTimes(2); | ||
expect(result.current).toMatchObject({ | ||
data: { | ||
x: resultTwo | ||
} | ||
}); | ||
}); | ||
@@ -1394,3 +1338,3 @@ }); | ||
resource: 'answer', | ||
params: (_ref32) => { | ||
params: _ref32 => { | ||
let { | ||
@@ -1413,4 +1357,3 @@ one, | ||
}; | ||
const wrapper = (_ref33) => { | ||
const wrapper = _ref33 => { | ||
let { | ||
@@ -1423,7 +1366,5 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useDataQuery.useDataQuery)(query, { | ||
variables: initialVariables | ||
@@ -1433,17 +1374,20 @@ }), { | ||
}); | ||
await waitForNextUpdate(); | ||
expect(mockSpy).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ | ||
params: initialVariables | ||
}), expect.anything()); | ||
(0, _reactHooks.act)(() => { | ||
await (0, _react.waitFor)(() => { | ||
expect(mockSpy).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ | ||
params: initialVariables | ||
}), expect.anything()); | ||
}); | ||
(0, _react.act)(() => { | ||
result.current.refetch(newVariables); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(mockSpy).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ | ||
params: { ...initialVariables, | ||
...newVariables | ||
} | ||
}), expect.anything()); | ||
await (0, _react.waitFor)(() => { | ||
expect(mockSpy).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ | ||
params: { | ||
...initialVariables, | ||
...newVariables | ||
} | ||
}), expect.anything()); | ||
}); | ||
}); | ||
}); | ||
}); |
@@ -7,10 +7,6 @@ "use strict"; | ||
exports.useQueryExecutor = void 0; | ||
var _react = require("react"); | ||
var _engine = require("../../engine"); | ||
var _useStaticInput = require("./useStaticInput"); | ||
const useQueryExecutor = (_ref) => { | ||
const useQueryExecutor = _ref => { | ||
let { | ||
@@ -52,10 +48,9 @@ execute, | ||
} : state); | ||
if (singular) { | ||
abort(); // Cleanup any in-progress fetches | ||
} | ||
const controller = new AbortController(); | ||
abortControllersRef.current.push(controller); | ||
variables.current = { ...variables.current, | ||
variables.current = { | ||
...variables.current, | ||
...newVariables | ||
@@ -78,3 +73,2 @@ }; | ||
} | ||
return new Promise(() => undefined); // Wait forever | ||
@@ -89,8 +83,8 @@ }).catch(error => { | ||
} | ||
return new Promise(() => undefined); // Don't throw errors in refetch promises, wait forever | ||
}); | ||
}, [abort, onComplete, onError, singular, theExecute]); // Don't include immediate or refetch as deps, otherwise unintentional refetches | ||
}, [abort, onComplete, onError, singular, theExecute]); | ||
// Don't include immediate or refetch as deps, otherwise unintentional refetches | ||
// may be triggered by changes to input, i.e. recreating the onComplete callback | ||
(0, _react.useEffect)(() => { | ||
@@ -100,3 +94,2 @@ if (immediate) { | ||
} | ||
return abort; | ||
@@ -111,3 +104,2 @@ }, []); // eslint-disable-line react-hooks/exhaustive-deps | ||
}; | ||
exports.useQueryExecutor = useQueryExecutor; |
"use strict"; | ||
var _reactHooks = require("@testing-library/react-hooks"); | ||
var _react = require("@testing-library/react"); | ||
var _useQueryExecutor = require("./useQueryExecutor"); | ||
const testError = new Error('TEST ERROR'); | ||
let theSignal; | ||
const execute = jest.fn(async (_ref) => { | ||
const execute = jest.fn(async _ref => { | ||
let { | ||
@@ -27,3 +25,3 @@ signal | ||
result | ||
} = (0, _reactHooks.renderHook)(() => (0, _useQueryExecutor.useQueryExecutor)({ | ||
} = (0, _react.renderHook)(() => (0, _useQueryExecutor.useQueryExecutor)({ | ||
execute, | ||
@@ -41,5 +39,4 @@ immediate: false, | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useQueryExecutor.useQueryExecutor)({ | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useQueryExecutor.useQueryExecutor)({ | ||
execute, | ||
@@ -54,7 +51,8 @@ immediate: true, | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
called: true, | ||
loading: false, | ||
data: 42 | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
called: true, | ||
loading: false, | ||
data: 42 | ||
}); | ||
}); | ||
@@ -64,5 +62,4 @@ }); | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useQueryExecutor.useQueryExecutor)({ | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useQueryExecutor.useQueryExecutor)({ | ||
execute, | ||
@@ -77,3 +74,3 @@ immediate: false, | ||
}); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
result.current.refetch(); | ||
@@ -85,7 +82,8 @@ }); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
called: true, | ||
loading: false, | ||
data: 42 | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
called: true, | ||
loading: false, | ||
data: 42 | ||
}); | ||
}); | ||
@@ -95,5 +93,4 @@ }); | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useQueryExecutor.useQueryExecutor)({ | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useQueryExecutor.useQueryExecutor)({ | ||
execute: failingExecute, | ||
@@ -108,3 +105,3 @@ immediate: false, | ||
}); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
result.current.refetch(); | ||
@@ -116,7 +113,8 @@ }); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
called: true, | ||
loading: false, | ||
error: testError | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
called: true, | ||
loading: false, | ||
error: testError | ||
}); | ||
}); | ||
@@ -127,5 +125,4 @@ }); | ||
result, | ||
waitForNextUpdate, | ||
rerender | ||
} = (0, _reactHooks.renderHook)((_ref2) => { | ||
} = (0, _react.renderHook)(_ref2 => { | ||
let { | ||
@@ -153,16 +150,16 @@ onComplete | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
called: true, | ||
loading: false, | ||
data: 42 | ||
await (0, _react.waitFor)(() => { | ||
expect(result.current).toMatchObject({ | ||
called: true, | ||
loading: false, | ||
data: 42 | ||
}); | ||
expect(theSignal && theSignal.aborted).toBe(false); | ||
expect(execute).toHaveBeenCalledTimes(1); | ||
}); | ||
expect(theSignal && theSignal.aborted).toBe(false); | ||
expect(execute).toHaveBeenCalledTimes(1); | ||
}); | ||
it('Should respect abort signal', async () => { | ||
const { | ||
result, | ||
waitForNextUpdate | ||
} = (0, _reactHooks.renderHook)(() => (0, _useQueryExecutor.useQueryExecutor)({ | ||
result | ||
} = (0, _react.renderHook)(() => (0, _useQueryExecutor.useQueryExecutor)({ | ||
execute, | ||
@@ -177,3 +174,3 @@ immediate: false, | ||
}); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
result.current.refetch(); | ||
@@ -185,3 +182,3 @@ }); | ||
}); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
result.current.abort(); | ||
@@ -188,0 +185,0 @@ }); |
@@ -7,5 +7,3 @@ "use strict"; | ||
exports.useStaticInput = void 0; | ||
var _react = require("react"); | ||
const useStaticInput = function (staticValue) { | ||
@@ -26,3 +24,2 @@ let { | ||
}; | ||
exports.useStaticInput = useStaticInput; |
"use strict"; | ||
var _reactHooks = require("@testing-library/react-hooks"); | ||
var _react = require("@testing-library/react"); | ||
var _useStaticInput = require("./useStaticInput"); | ||
describe('useStaticInput', () => { | ||
@@ -18,3 +16,3 @@ const originalWarn = console.warn; | ||
result | ||
} = (0, _reactHooks.renderHook)(() => (0, _useStaticInput.useStaticInput)(42)); | ||
} = (0, _react.renderHook)(() => (0, _useStaticInput.useStaticInput)(42)); | ||
expect(result.current[0]).toBe(42); | ||
@@ -27,3 +25,3 @@ expect(mockWarn).not.toHaveBeenCalled(); | ||
rerender | ||
} = (0, _reactHooks.renderHook)((_ref) => { | ||
} = (0, _react.renderHook)(_ref => { | ||
let { | ||
@@ -49,3 +47,3 @@ value | ||
rerender | ||
} = (0, _reactHooks.renderHook)((_ref2) => { | ||
} = (0, _react.renderHook)(_ref2 => { | ||
let { | ||
@@ -78,3 +76,3 @@ value | ||
rerender | ||
} = (0, _reactHooks.renderHook)((_ref3) => { | ||
} = (0, _react.renderHook)(_ref3 => { | ||
let { | ||
@@ -104,3 +102,3 @@ value | ||
rerender | ||
} = (0, _reactHooks.renderHook)((_ref4) => { | ||
} = (0, _react.renderHook)(_ref4 => { | ||
let { | ||
@@ -119,3 +117,3 @@ value | ||
expect(value).toBe(42); | ||
(0, _reactHooks.act)(() => { | ||
(0, _react.act)(() => { | ||
setValue(54); | ||
@@ -142,3 +140,3 @@ }); | ||
rerender | ||
} = (0, _reactHooks.renderHook)((_ref5) => { | ||
} = (0, _react.renderHook)(_ref5 => { | ||
let { | ||
@@ -145,0 +143,0 @@ value |
@@ -72,23 +72,12 @@ "use strict"; | ||
}); | ||
var _CustomDataProvider = require("./components/CustomDataProvider"); | ||
var _DataMutation = require("./components/DataMutation"); | ||
var _DataProvider = require("./components/DataProvider"); | ||
var _DataQuery = require("./components/DataQuery"); | ||
var _DataContext = require("./context/DataContext"); | ||
var _defaultContext = require("./context/defaultContext"); | ||
var _useDataEngine = require("./hooks/useDataEngine"); | ||
var _useDataMutation = require("./hooks/useDataMutation"); | ||
var _useDataQuery = require("./hooks/useDataQuery"); | ||
var _useQueryExecutor = require("./hooks/useQueryExecutor"); | ||
var _useStaticInput = require("./hooks/useStaticInput"); |
"use strict"; | ||
require("@testing-library/jest-dom/extend-expect"); | ||
require("@testing-library/jest-dom"); | ||
process.on('unhandledRejection', err => { | ||
throw err; | ||
}); |
@@ -9,4 +9,3 @@ import { render, waitFor } from '@testing-library/react'; | ||
}; | ||
const wrapper = (_ref) => { | ||
const wrapper = _ref => { | ||
let { | ||
@@ -19,5 +18,4 @@ children | ||
}; | ||
const renderFunction = jest.fn(() => null); | ||
render( /*#__PURE__*/React.createElement(DataQuery, { | ||
render(/*#__PURE__*/React.createElement(DataQuery, { | ||
query: { | ||
@@ -52,4 +50,3 @@ answer: { | ||
}; | ||
const wrapper = (_ref2) => { | ||
const wrapper = _ref2 => { | ||
let { | ||
@@ -62,5 +59,4 @@ children | ||
}; | ||
const renderFunction = jest.fn(() => null); | ||
render( /*#__PURE__*/React.createElement(DataQuery, { | ||
render(/*#__PURE__*/React.createElement(DataQuery, { | ||
query: { | ||
@@ -67,0 +63,0 @@ test: { |
@@ -17,4 +17,3 @@ import { render, waitFor, act } from '@testing-library/react'; | ||
}; | ||
const wrapper = (_ref) => { | ||
const wrapper = _ref => { | ||
let { | ||
@@ -27,5 +26,4 @@ children | ||
}; | ||
const renderSpy = jest.fn(() => null); | ||
render( /*#__PURE__*/React.createElement(DataMutation, { | ||
render(/*#__PURE__*/React.createElement(DataMutation, { | ||
mutation: mutation | ||
@@ -32,0 +30,0 @@ }, renderSpy), { |
@@ -1,7 +0,7 @@ | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
import { getMutationFetchType } from './helpers/getMutationFetchType'; | ||
import { resolveDynamicQuery } from './helpers/resolveDynamicQuery'; | ||
import { validateResourceQuery, validateResourceQueries } from './helpers/validate'; | ||
const reduceResponses = (responses, names) => responses.reduce((out, response, idx) => { | ||
@@ -11,10 +11,7 @@ out[names[idx]] = response; | ||
}, {}); | ||
export class DataEngine { | ||
constructor(link) { | ||
_defineProperty(this, "link", void 0); | ||
this.link = link; | ||
} | ||
query(query) { | ||
@@ -43,3 +40,2 @@ let { | ||
} | ||
mutate(mutation) { | ||
@@ -66,4 +62,3 @@ let { | ||
} | ||
} | ||
export default DataEngine; |
@@ -17,3 +17,2 @@ import { DataEngine } from './DataEngine'; | ||
} | ||
return { | ||
@@ -20,0 +19,0 @@ type, |
@@ -20,3 +20,3 @@ import { resolveDynamicQuery } from './resolveDynamicQuery'; | ||
resource: 'test', | ||
id: (_ref) => { | ||
id: _ref => { | ||
let { | ||
@@ -27,3 +27,3 @@ id | ||
}, | ||
params: (_ref2) => { | ||
params: _ref2 => { | ||
let { | ||
@@ -37,3 +37,3 @@ page | ||
}, | ||
data: (_ref3) => { | ||
data: _ref3 => { | ||
let { | ||
@@ -40,0 +40,0 @@ bar |
@@ -8,33 +8,24 @@ import { InvalidQueryError } from '../types/InvalidQueryError'; | ||
} | ||
if (typeof query !== 'object') { | ||
return ['A query or mutation must be a javascript object']; | ||
} | ||
const errors = []; | ||
if (!query.resource || typeof query.resource !== 'string') { | ||
errors.push('Property resource must be a string'); | ||
} | ||
if (type === 'create' && query.id) { | ||
errors.push("Mutation type 'create' does not support property 'id'"); | ||
} | ||
if (query.id && typeof query.id !== 'string') { | ||
errors.push('Property id must be a string'); | ||
} | ||
if (query.params && typeof query.params !== 'object') { | ||
errors.push('Property params must be an object'); | ||
} | ||
if (type === 'delete' && query.data) { | ||
errors.push("Mutation type 'delete' does not support property 'data'"); | ||
} | ||
if (type === 'json-patch' && !Array.isArray(query.data)) { | ||
errors.push("Mutation type 'json-patch' requires property 'data' to be of type Array"); | ||
} | ||
const invalidKeys = Object.keys(query).filter(k => !validQueryKeys.includes(k)); | ||
@@ -48,3 +39,2 @@ invalidKeys.forEach(k => { | ||
let names = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; | ||
if (names.length !== queries.length) { | ||
@@ -55,5 +45,3 @@ for (let i = names.length; i < queries.length; ++i) { | ||
} | ||
const errors = queries.reduce((errors, query, i) => errors.concat(getResourceQueryErrors('read', query).map(e => `[${names[i]}] ${e}`)), []); | ||
if (errors.length) { | ||
@@ -65,3 +53,2 @@ throw new InvalidQueryError(errors); | ||
const errors = getResourceQueryErrors(type, query); | ||
if (errors.length) { | ||
@@ -68,0 +55,0 @@ throw new InvalidQueryError(errors); |
@@ -1,3 +0,4 @@ | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
export class FetchError extends Error { | ||
@@ -11,11 +12,7 @@ constructor(_ref) { | ||
super(message); | ||
_defineProperty(this, "type", void 0); | ||
_defineProperty(this, "details", void 0); | ||
this.type = type; | ||
this.details = details; | ||
} | ||
} |
@@ -1,14 +0,11 @@ | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
export class InvalidQueryError extends Error { | ||
constructor(errors) { | ||
super(`Invalid query\n${errors.map(e => ' - ' + e).join('\n')}`); | ||
_defineProperty(this, "type", 'invalid-query'); | ||
_defineProperty(this, "details", void 0); | ||
this.details = errors; | ||
} | ||
} |
@@ -1,3 +0,4 @@ | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
export class CustomDataLink { | ||
@@ -9,9 +10,5 @@ constructor(customData) { | ||
} = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
_defineProperty(this, "failOnMiss", void 0); | ||
_defineProperty(this, "loadForever", void 0); | ||
_defineProperty(this, "data", void 0); | ||
this.data = customData; | ||
@@ -21,3 +18,2 @@ this.failOnMiss = failOnMiss; | ||
} | ||
async executeResourceQuery(type, query, options) { | ||
@@ -27,5 +23,3 @@ if (this.loadForever) { | ||
} | ||
const customResource = this.data[query.resource]; | ||
if (customResource === undefined) { | ||
@@ -35,6 +29,4 @@ if (this.failOnMiss) { | ||
} | ||
return Promise.resolve(null); | ||
} | ||
switch (typeof customResource) { | ||
@@ -46,11 +38,8 @@ case 'string': | ||
return customResource; | ||
case 'function': | ||
{ | ||
const result = await customResource(type, query, options); | ||
if (typeof result === 'undefined' && this.failOnMiss) { | ||
throw new Error(`The custom function for resource ${query.resource} must always return a value but returned ${result}`); | ||
} | ||
return result || null; | ||
@@ -60,3 +49,2 @@ } | ||
} | ||
} |
@@ -1,10 +0,9 @@ | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
export class ErrorLink { | ||
constructor(errorMessage) { | ||
_defineProperty(this, "errorMessage", void 0); | ||
this.errorMessage = errorMessage; | ||
} | ||
executeResourceQuery() { | ||
@@ -14,3 +13,2 @@ console.error(this.errorMessage); | ||
} | ||
} |
@@ -1,3 +0,4 @@ | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
import { fetchData } from './RestAPILink/fetchData'; | ||
@@ -10,7 +11,4 @@ import { joinPath } from './RestAPILink/path'; | ||
_defineProperty(this, "config", void 0); | ||
_defineProperty(this, "versionedApiPath", void 0); | ||
_defineProperty(this, "unversionedApiPath", void 0); | ||
this.config = config; | ||
@@ -20,7 +18,5 @@ this.versionedApiPath = joinPath('api', String(config.apiVersion)); | ||
} | ||
fetch(path, options) { | ||
return fetchData(joinPath(this.config.baseUrl, path), options); | ||
} | ||
executeResourceQuery(type, query, _ref) { | ||
@@ -32,3 +28,2 @@ let { | ||
} | ||
} |
@@ -5,18 +5,16 @@ import { FetchError } from '../../engine'; | ||
const accessError = response.status === 401 || response.status === 403 || response.status === 409; | ||
if (accessError) { | ||
let message; | ||
let details = {}; | ||
try { | ||
details = await response.json(); | ||
message = details.message; | ||
} catch (e) {// Do nothing | ||
} // Set a message in case of invalid json, or json without 'message' property | ||
} catch (e) { | ||
// Do nothing | ||
} | ||
// Set a message in case of invalid json, or json without 'message' property | ||
if (!message) { | ||
message = response.status === 401 ? 'Unauthorized' : 'Forbidden'; | ||
} | ||
throw new FetchError({ | ||
@@ -28,12 +26,10 @@ type: 'access', | ||
} | ||
if (response.status < 200 || response.status >= 400) { | ||
const message = `An unknown error occurred - ${response.statusText} (${response.status})`; | ||
let details = {}; | ||
try { | ||
details = await response.json(); | ||
} catch (e) {// We can leave details as is if parsing fails | ||
} catch (e) { | ||
// We can leave details as is if parsing fails | ||
} | ||
throw new FetchError({ | ||
@@ -45,3 +41,2 @@ type: 'unknown', | ||
} | ||
return response; | ||
@@ -51,3 +46,4 @@ }; | ||
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
return fetch(url, { ...options, | ||
return fetch(url, { | ||
...options, | ||
credentials: 'include', | ||
@@ -66,15 +62,15 @@ headers: { | ||
}).then(parseStatus).then(async response => { | ||
const contentType = parseContentType(response.headers.get('Content-Type')); // 'application/json' | ||
const contentType = parseContentType(response.headers.get('Content-Type')); | ||
// 'application/json' | ||
if (contentType === 'application/json') { | ||
return await response.json(); // Will throw if invalid JSON! | ||
} // 'text/*' | ||
} | ||
// 'text/*' | ||
if (/^text\/[a-z0-9.-]+$/.test(contentType)) { | ||
return await response.text(); | ||
} | ||
return await response.blob(); | ||
}); | ||
} |
@@ -6,7 +6,12 @@ /* | ||
*/ | ||
export const normativeMetadataResources = ['programDataElements', 'indicatorTypes', 'programs', 'optionGroups', 'programRuleVariables', 'reports', 'users', 'constants', 'externalMapLayers', 'analyticsTableHooks', 'pushAnalysis', 'oAuth2Clients', 'validationRules', 'reportTables', 'userGroups', 'sqlViews', 'sections', 'validationNotificationTemplates', 'optionGroupSets', 'organisationUnitGroupSets', 'trackedEntityAttributes', 'dashboardItems', 'categoryCombos', 'programSections', 'trackedEntityTypes', 'dataSetNotificationTemplates', 'maps', 'dataApprovalWorkflows', 'programStages', 'categoryOptionGroups', 'relationshipTypes', 'validationRuleGroups', 'predictors', 'dataSets', 'options', 'organisationUnitLevels', 'dataEntryForms', 'predictorGroups', 'dataElementGroupSets', 'programIndicatorGroups', 'dataApprovalLevels', 'organisationUnits', 'programIndicators', 'dataElements', 'mapViews', 'categories', 'categoryOptionCombos', 'documents', 'indicators', 'optionSets', 'interpretations', 'programRuleActions', 'dataElementGroups', 'attributes', 'validationResults', 'categoryOptions', 'indicatorGroupSets', 'messageConversations', 'dashboards', 'programNotificationTemplates', 'programStageSections', 'legendSets', 'organisationUnitGroups', 'visualizations', 'indicatorGroups', 'programTrackedEntityAttributeGroups', 'programRules', 'categoryOptionGroupSets', 'userRoles', 'eventFilters', 'eventReports', 'eventCharts', 'smsCommands', 'jobConfigurations', 'minMaxDataElements', 'charts', 'dataElementOperands', // These exist and appear to accept field declarations, but have abnormal behavior when it comes to viewing collections and paging results | ||
'trackedEntityInstance', 'relationships']; // Including non-normative resources listed under /api/resources for future follow-up | ||
export const nonNormativeMetadataResources = ['trackedEntityAttributeValues', 'programInstances', 'expressions', 'programStageInstances', 'externalFileResources', 'icons', 'fileResources', 'metadataVersions', 'dataStores', // This doesn't exist, but is listed as the plural of 'dataStore' in /api/resources | ||
export const normativeMetadataResources = ['programDataElements', 'indicatorTypes', 'programs', 'optionGroups', 'programRuleVariables', 'reports', 'users', 'constants', 'externalMapLayers', 'analyticsTableHooks', 'pushAnalysis', 'oAuth2Clients', 'validationRules', 'reportTables', 'userGroups', 'sqlViews', 'sections', 'validationNotificationTemplates', 'optionGroupSets', 'organisationUnitGroupSets', 'trackedEntityAttributes', 'dashboardItems', 'categoryCombos', 'programSections', 'trackedEntityTypes', 'dataSetNotificationTemplates', 'maps', 'dataApprovalWorkflows', 'programStages', 'categoryOptionGroups', 'relationshipTypes', 'validationRuleGroups', 'predictors', 'dataSets', 'options', 'organisationUnitLevels', 'dataEntryForms', 'predictorGroups', 'dataElementGroupSets', 'programIndicatorGroups', 'dataApprovalLevels', 'organisationUnits', 'programIndicators', 'dataElements', 'mapViews', 'categories', 'categoryOptionCombos', 'documents', 'indicators', 'optionSets', 'interpretations', 'programRuleActions', 'dataElementGroups', 'attributes', 'validationResults', 'categoryOptions', 'indicatorGroupSets', 'messageConversations', 'dashboards', 'programNotificationTemplates', 'programStageSections', 'legendSets', 'organisationUnitGroups', 'visualizations', 'indicatorGroups', 'programTrackedEntityAttributeGroups', 'programRules', 'categoryOptionGroupSets', 'userRoles', 'eventFilters', 'eventReports', 'eventCharts', 'smsCommands', 'jobConfigurations', 'minMaxDataElements', 'charts', 'dataElementOperands', | ||
// These exist and appear to accept field declarations, but have abnormal behavior when it comes to viewing collections and paging results | ||
'trackedEntityInstance', 'relationships']; | ||
// Including non-normative resources listed under /api/resources for future follow-up | ||
export const nonNormativeMetadataResources = ['trackedEntityAttributeValues', 'programInstances', 'expressions', 'programStageInstances', 'externalFileResources', 'icons', 'fileResources', 'metadataVersions', 'dataStores', | ||
// This doesn't exist, but is listed as the plural of 'dataStore' in /api/resources | ||
// Known but missing from /api/resources | ||
'userDataStore', 'apps']; |
@@ -5,5 +5,4 @@ export const joinPath = function () { | ||
} | ||
const realParts = parts.filter(part => !!part); | ||
return realParts.map(part => part.replace(/^\/+|\/+$/g, '')).join('/'); | ||
}; |
import { requestContentType, requestBodyForContentType, requestHeadersForContentType } from './queryToRequestOptions/requestContentType'; | ||
const getMethod = type => { | ||
@@ -7,16 +6,11 @@ switch (type) { | ||
return 'POST'; | ||
case 'read': | ||
return 'GET'; | ||
case 'update': | ||
case 'json-patch': | ||
return 'PATCH'; | ||
case 'replace': | ||
return 'PUT'; | ||
case 'delete': | ||
return 'DELETE'; | ||
default: | ||
@@ -26,3 +20,2 @@ throw new Error(`Unknown type ${type}`); | ||
}; | ||
export const queryToRequestOptions = (type, query, signal) => { | ||
@@ -29,0 +22,0 @@ const contentType = requestContentType(type, query); |
@@ -6,2 +6,3 @@ /* | ||
*/ | ||
// Post to 'dataValues' (send/update a data value; endpoint doesn't support JSON) | ||
@@ -14,4 +15,5 @@ // For file-uploads too | ||
return type === 'create' && (resource === 'dataValues' || resource === 'dataValues/file'); | ||
}; // POST to 'fileResources' (upload a file resource) | ||
}; | ||
// POST to 'fileResources' (upload a file resource) | ||
export const isFileResourceUpload = (type, _ref2) => { | ||
@@ -22,4 +24,5 @@ let { | ||
return type === 'create' && resource === 'fileResources'; | ||
}; // POST to 'messageConversations/attachments' (upload a message conversation attachment) | ||
}; | ||
// POST to 'messageConversations/attachments' (upload a message conversation attachment) | ||
export const isMessageConversationAttachment = (type, _ref3) => { | ||
@@ -30,4 +33,5 @@ let { | ||
return type === 'create' && resource === 'messageConversations/attachments'; | ||
}; // POST to `staticContent/${key}` (upload staticContent: logo_banner | logo_front) | ||
}; | ||
// POST to `staticContent/${key}` (upload staticContent: logo_banner | logo_front) | ||
export const isStaticContentUpload = (type, _ref4) => { | ||
@@ -39,4 +43,5 @@ let { | ||
return type === 'create' && pattern.test(resource); | ||
}; // POST to 'apps' (install an app) | ||
}; | ||
// POST to 'apps' (install an app) | ||
export const isAppInstall = (type, _ref5) => { | ||
@@ -43,0 +48,0 @@ let { |
import * as multipartFormDataMatchers from './multipartFormDataMatchers'; | ||
import * as textPlainMatchers from './textPlainMatchers'; | ||
import * as xWwwFormUrlencodedMatchers from './xWwwFormUrlencodedMatchers'; | ||
const resourceExpectsTextPlain = (type, query) => Object.values(textPlainMatchers).some(textPlainMatcher => textPlainMatcher(type, query)); | ||
const resourceExpectsMultipartFormData = (type, query) => Object.values(multipartFormDataMatchers).some(multipartFormDataMatcher => multipartFormDataMatcher(type, query)); | ||
const resourceExpectsXWwwFormUrlencoded = (type, query) => Object.values(xWwwFormUrlencodedMatchers).some(xWwwFormUrlencodedMatcher => xWwwFormUrlencodedMatcher(type, query)); | ||
const convertData = (data, initialValue) => { | ||
const dataEntries = Object.entries(data); | ||
if (dataEntries.length === 0) { | ||
throw new Error(`Could not convert data to ${initialValue.constructor.name}: object does not have own enumerable string-keyed properties`); | ||
} | ||
return dataEntries.reduce((convertedData, _ref) => { | ||
@@ -24,3 +18,2 @@ let [key, value] = _ref; | ||
}; | ||
export const requestContentType = (type, query) => { | ||
@@ -30,19 +23,14 @@ if (!query.data) { | ||
} | ||
if (type === 'json-patch') { | ||
return 'application/json-patch+json'; | ||
} | ||
if (resourceExpectsTextPlain(type, query)) { | ||
return 'text/plain'; | ||
} | ||
if (resourceExpectsMultipartFormData(type, query)) { | ||
return 'multipart/form-data'; | ||
} | ||
if (resourceExpectsXWwwFormUrlencoded(type, query)) { | ||
return 'application/x-www-form-urlencoded'; | ||
} | ||
return 'application/json'; | ||
@@ -61,3 +49,2 @@ }; | ||
} | ||
return { | ||
@@ -71,21 +58,17 @@ 'Content-Type': contentType | ||
} = _ref2; | ||
if (typeof data === 'undefined') { | ||
return undefined; | ||
} | ||
if (contentType === 'application/json' || contentType === 'application/json-patch+json') { | ||
return JSON.stringify(data); | ||
} | ||
if (contentType === 'multipart/form-data') { | ||
return convertData(data, new FormData()); | ||
} | ||
if (contentType === 'application/x-www-form-urlencoded') { | ||
return convertData(data, new URLSearchParams()); | ||
} // 'text/plain' | ||
} | ||
// 'text/plain' | ||
return data; | ||
}; |
@@ -11,2 +11,3 @@ /* | ||
*/ | ||
// POST to `messageConversations/${id}` (reply to a messagConversation) | ||
@@ -19,4 +20,5 @@ export const isReplyToMessageConversation = (type, _ref) => { | ||
return type === 'create' && pattern.test(resource); | ||
}; // POST to 'messageConversations/feedback' (create a feedback message) | ||
}; | ||
// POST to 'messageConversations/feedback' (create a feedback message) | ||
export const isCreateFeedbackMessage = (type, _ref2) => { | ||
@@ -27,4 +29,5 @@ let { | ||
return type === 'create' && resource === 'messageConversations/feedback'; | ||
}; // POST `interpretations/${objectType}/${id}` (add an interpretation to a visualization) | ||
}; | ||
// POST `interpretations/${objectType}/${id}` (add an interpretation to a visualization) | ||
export const isCreateInterpretation = (type, _ref3) => { | ||
@@ -36,4 +39,5 @@ let { | ||
return type === 'create' && pattern.test(resource); | ||
}; // PUT to `interpretations/${id}` (update an interpretation) | ||
}; | ||
// PUT to `interpretations/${id}` (update an interpretation) | ||
export const isUpdateInterpretation = (type, _ref4) => { | ||
@@ -44,9 +48,6 @@ let { | ||
} = _ref4; | ||
if (type !== 'replace') { | ||
return false; | ||
} | ||
let resourcePattern; | ||
if (id) { | ||
@@ -57,7 +58,7 @@ resourcePattern = /^interpretations$/; | ||
} | ||
resourcePattern = /^interpretations\/[a-zA-Z0-9]{11}$/; | ||
return resourcePattern.test(resource); | ||
}; // POST to `interpretations/${id}/comments` (comment on an interpretation) | ||
}; | ||
// POST to `interpretations/${id}/comments` (comment on an interpretation) | ||
export const isCommentOnInterpretation = (type, _ref5) => { | ||
@@ -69,5 +70,6 @@ let { | ||
return type === 'create' && pattern.test(resource); | ||
}; // PUT to `interpretations/${interpretationId}/comments/${commentId}` | ||
}; | ||
// PUT to `interpretations/${interpretationId}/comments/${commentId}` | ||
// (update an interpretation comment) | ||
export const isInterpretationCommentUpdate = (type, _ref6) => { | ||
@@ -78,7 +80,5 @@ let { | ||
} = _ref6; | ||
if (type !== 'replace') { | ||
return false; | ||
} | ||
if (id) { | ||
@@ -90,8 +90,8 @@ const idPatternLong = /^[a-zA-Z0-9]{11}\/comments\/[a-zA-Z0-9]{11}$/; | ||
} | ||
const pattern = /^interpretations\/[a-zA-Z0-9]{11}\/comments\/[a-zA-Z0-9]{11}$/; | ||
return pattern.test(resource); | ||
}; // POST to `systemSettings/${settingKey}` or `userSettings/${settingKey}` | ||
}; | ||
// POST to `systemSettings/${settingKey}` or `userSettings/${settingKey}` | ||
// (add or update a single system or user setting) | ||
export const isAddOrUpdateSystemOrUserSetting = (type, _ref7) => { | ||
@@ -104,5 +104,6 @@ let { | ||
return type === 'create' && pattern.test(resource); | ||
}; // POST to `configuration/${configurationProperty}` | ||
}; | ||
// POST to `configuration/${configurationProperty}` | ||
// (add or update a single configuration property) | ||
export const addOrUpdateConfigurationProperty = (type, _ref8) => { | ||
@@ -116,4 +117,5 @@ let { | ||
return type === 'create' && !!match && match[2] !== 'corsWhitelist'; | ||
}; // POST to 'synchronization/metadataPull' (install a metadata package) | ||
}; | ||
// POST to 'synchronization/metadataPull' (install a metadata package) | ||
export const isMetadataPackageInstallation = (type, _ref9) => { | ||
@@ -124,4 +126,5 @@ let { | ||
return type === 'create' && resource === 'synchronization/metadataPull'; | ||
}; // POST to 'indicators/expression/description' or 'programIndicator/expression/description' (validate an expression) | ||
}; | ||
// POST to 'indicators/expression/description' or 'programIndicator/expression/description' (validate an expression) | ||
export const isExpressionDescriptionValidation = (type, _ref10) => { | ||
@@ -128,0 +131,0 @@ let { |
import { joinPath } from './path'; | ||
import { validateResourceQuery } from './validateQuery'; | ||
const encodeQueryParameter = param => { | ||
@@ -8,21 +7,15 @@ if (Array.isArray(param)) { | ||
} | ||
if (typeof param === 'string') { | ||
return encodeURIComponent(param); | ||
} | ||
if (typeof param === 'number' || typeof param === 'boolean') { | ||
return String(param); | ||
} | ||
if (typeof param === 'object') { | ||
throw new Error('Object parameter mappings not yet implemented'); | ||
} | ||
throw new Error('Unknown parameter type'); | ||
}; | ||
const queryParametersMapToArray = params => Object.keys(params).reduce((out, key) => { | ||
const value = params[key]; | ||
if (key === 'filter' && Array.isArray(value)) { | ||
@@ -41,9 +34,7 @@ value.forEach(item => { | ||
} | ||
return out; | ||
}, []); | ||
const queryParametersToQueryString = params => { | ||
const expandedParams = queryParametersMapToArray(params); | ||
return expandedParams.map((_ref) => { | ||
return expandedParams.map(_ref => { | ||
let { | ||
@@ -56,26 +47,19 @@ key, | ||
}; | ||
const actionPrefix = 'action::'; | ||
const isAction = resource => resource.startsWith(actionPrefix); | ||
const makeActionPath = resource => joinPath('dhis-web-commons', `${resource.substr(actionPrefix.length)}.action`); | ||
const skipApiVersion = (resource, config) => { | ||
if (resource === 'tracker' || resource.startsWith('tracker/')) { | ||
var _config$serverVersion, _config$serverVersion2; | ||
if (!((_config$serverVersion = config.serverVersion) !== null && _config$serverVersion !== void 0 && _config$serverVersion.minor) || ((_config$serverVersion2 = config.serverVersion) === null || _config$serverVersion2 === void 0 ? void 0 : _config$serverVersion2.minor) < 38) { | ||
return true; | ||
} | ||
} // The `/api/ping` endpoint is unversioned | ||
} | ||
// The `/api/ping` endpoint is unversioned | ||
if (resource === 'ping') { | ||
return true; | ||
} | ||
return false; | ||
}; | ||
export const queryToResourcePath = (link, query, type) => { | ||
@@ -90,8 +74,6 @@ const { | ||
validateResourceQuery(query, type); | ||
if (Object.keys(params).length) { | ||
return `${base}?${queryParametersToQueryString(params)}`; | ||
} | ||
return base; | ||
}; |
import { RestAPILink } from '../RestAPILink'; | ||
import { queryToResourcePath } from './queryToResourcePath'; | ||
const createLink = config => new RestAPILink(config); | ||
const defaultConfig = { | ||
@@ -163,3 +161,4 @@ basePath: '<base>', | ||
}; | ||
const v38config = { ...defaultConfig, | ||
const v38config = { | ||
...defaultConfig, | ||
serverVersion: { | ||
@@ -166,0 +165,0 @@ major: 2, |
import { normativeMetadataResources } from './metadataResources'; | ||
const validatePagination = (query, warn) => { | ||
var _query$params, _query$params2; | ||
if (!normativeMetadataResources.includes(query.resource)) { | ||
return true; | ||
} | ||
if (((_query$params = query.params) === null || _query$params === void 0 ? void 0 : _query$params.paging) === false || ((_query$params2 = query.params) === null || _query$params2 === void 0 ? void 0 : _query$params2.paging) === 'false') { | ||
warn('Data queries with paging=false are deprecated and should not be used!', query); | ||
return false; | ||
} // TODO: validate sub-resource pagination (i.e. fields=users~paging(1,50)[name] ) | ||
} | ||
// TODO: validate sub-resource pagination (i.e. fields=users~paging(1,50)[name] ) | ||
return true; | ||
}; | ||
const validateDeclarativeFields = (query, warn) => { | ||
var _query$params3; | ||
if (!normativeMetadataResources.includes(query.resource)) { | ||
return true; | ||
} | ||
if (!((_query$params3 = query.params) !== null && _query$params3 !== void 0 && _query$params3.fields)) { | ||
@@ -31,5 +26,3 @@ warn('Data queries should always specify fields to return', query); | ||
var _fields; | ||
let fields = undefined; | ||
if (typeof query.params.fields === 'string') { | ||
@@ -40,3 +33,2 @@ fields = query.params.fields.split(',').map(field => field.trim()); | ||
} | ||
if ((_fields = fields) !== null && _fields !== void 0 && _fields.find(field => field.match(/(^\*$|^:.+)/))) { | ||
@@ -46,15 +38,12 @@ warn('Data queries should not use wildcard or dynamic field groups', query.params.fields, query); | ||
} | ||
} // TODO: validate sub-resource wildcard fields (i.e. fields=users[*]) | ||
} | ||
// TODO: validate sub-resource wildcard fields (i.e. fields=users[*]) | ||
return true; | ||
}; | ||
export const validateResourceQuery = (query, type) => { | ||
let valid = true; | ||
if (process.env.NODE_ENV === 'development') { | ||
// Support build-time dead code elimination in production | ||
const warn = console.warn; | ||
if (type === 'read') { | ||
@@ -65,4 +54,3 @@ valid = validatePagination(query, warn) && valid; | ||
} | ||
return valid; | ||
}; |
@@ -7,3 +7,3 @@ import React from 'react'; | ||
import { queryClientOptions as queryClientDefaults } from './DataProvider'; | ||
export const CustomDataProvider = (_ref) => { | ||
export const CustomDataProvider = _ref => { | ||
let { | ||
@@ -10,0 +10,0 @@ children, |
import { useDataMutation } from '../hooks/useDataMutation'; | ||
export const DataMutation = (_ref) => { | ||
export const DataMutation = _ref => { | ||
let { | ||
@@ -4,0 +4,0 @@ mutation, |
/* eslint-disable react/no-unused-prop-types */ | ||
import { useConfig } from '@dhis2/app-service-config'; | ||
@@ -26,3 +27,4 @@ import React from 'react'; | ||
export const DataProvider = props => { | ||
const config = { ...useConfig(), | ||
const config = { | ||
...useConfig(), | ||
...props | ||
@@ -29,0 +31,0 @@ }; |
@@ -10,3 +10,3 @@ import { render } from '@testing-library/react'; | ||
const renderFunction = jest.fn(); | ||
render( /*#__PURE__*/React.createElement(DataProvider, { | ||
render(/*#__PURE__*/React.createElement(DataProvider, { | ||
baseUrl: "test", | ||
@@ -13,0 +13,0 @@ apiVersion: 42 |
import { useDataQuery } from '../hooks/useDataQuery'; | ||
export const DataQuery = (_ref) => { | ||
export const DataQuery = _ref => { | ||
let { | ||
@@ -4,0 +4,0 @@ query, |
@@ -9,7 +9,8 @@ import { stableVariablesHash } from './stableVariablesHash'; | ||
}; | ||
} // Use cached hash if it exists | ||
} | ||
// Use cached hash if it exists | ||
const currentHash = previousHash || stableVariablesHash(previousVariables); | ||
const mergedVariables = { ...previousVariables, | ||
const mergedVariables = { | ||
...previousVariables, | ||
...newVariables | ||
@@ -16,0 +17,0 @@ }; |
@@ -44,3 +44,4 @@ import { mergeAndCompareVariables } from './mergeAndCompareVariables'; | ||
}; | ||
const expectedMergedVariables = { ...testVariables, | ||
const expectedMergedVariables = { | ||
...testVariables, | ||
...newVariables | ||
@@ -47,0 +48,0 @@ }; |
function hasObjectPrototype(o) { | ||
return Object.prototype.toString.call(o) === '[object Object]'; | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
} | ||
// eslint-disable-next-line @typescript-eslint/ban-types | ||
export function isPlainObject(o) { | ||
if (!hasObjectPrototype(o)) { | ||
return false; | ||
} // If has modified constructor | ||
} | ||
// If has modified constructor | ||
const ctor = o.constructor; | ||
if (typeof ctor === 'undefined') { | ||
return true; | ||
} // If has modified prototype | ||
} | ||
// If has modified prototype | ||
const prot = ctor.prototype; | ||
if (!hasObjectPrototype(prot)) { | ||
return false; | ||
} // If constructor does not have an Object-specific method | ||
} | ||
// If constructor does not have an Object-specific method | ||
if (!Object.prototype.hasOwnProperty.call(prot, 'isPrototypeOf')) { | ||
return false; | ||
} // Most likely a plain Object | ||
} | ||
// Most likely a plain Object | ||
return true; | ||
} | ||
/** | ||
@@ -39,3 +38,2 @@ * Hashes the value into a stable hash. | ||
let hash; | ||
try { | ||
@@ -49,4 +47,3 @@ hash = JSON.stringify(value, (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => { | ||
} | ||
return hash; | ||
} |
@@ -1,2 +0,2 @@ | ||
import { renderHook, act } from '@testing-library/react-hooks'; | ||
import { renderHook, act, waitFor } from '@testing-library/react'; | ||
import * as React from 'react'; | ||
@@ -18,4 +18,3 @@ import { CustomDataProvider } from '../components/CustomDataProvider'; | ||
}; | ||
const wrapper = (_ref) => { | ||
const wrapper = _ref => { | ||
let { | ||
@@ -28,6 +27,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
result | ||
} = renderHook(() => useDataMutation(mutation), { | ||
@@ -71,4 +68,3 @@ wrapper | ||
}; | ||
const wrapper = (_ref2) => { | ||
const wrapper = _ref2 => { | ||
let { | ||
@@ -81,6 +77,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
result | ||
} = renderHook(() => useDataMutation(mutation, { | ||
@@ -117,4 +111,3 @@ lazy: false | ||
}; | ||
const wrapper = (_ref3) => { | ||
const wrapper = _ref3 => { | ||
let { | ||
@@ -127,6 +120,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
result | ||
} = renderHook(() => useDataMutation(mutation, { | ||
@@ -168,4 +159,3 @@ onComplete | ||
}; | ||
const wrapper = (_ref4) => { | ||
const wrapper = _ref4 => { | ||
let { | ||
@@ -178,6 +168,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
result | ||
} = renderHook(() => useDataMutation(mutation, { | ||
@@ -208,3 +196,3 @@ onError | ||
resource: 'answer', | ||
id: (_ref5) => { | ||
id: _ref5 => { | ||
let { | ||
@@ -223,4 +211,3 @@ id | ||
}; | ||
const wrapper = (_ref6) => { | ||
const wrapper = _ref6 => { | ||
let { | ||
@@ -233,6 +220,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
result | ||
} = renderHook(() => useDataMutation(mutation, { | ||
@@ -271,4 +256,3 @@ lazy: false, | ||
}; | ||
const wrapper = (_ref7) => { | ||
const wrapper = _ref7 => { | ||
let { | ||
@@ -281,3 +265,2 @@ children | ||
}; | ||
const engineHook = renderHook(() => useDataEngine(), { | ||
@@ -289,2 +272,3 @@ wrapper | ||
}); | ||
/** | ||
@@ -294,3 +278,2 @@ * Ideally we'd check referential equality here with .toBe, but since | ||
*/ | ||
expect(mutationHook.result.current[1].engine).toStrictEqual(engineHook.result.current); | ||
@@ -309,4 +292,3 @@ }); | ||
}; | ||
const wrapper = (_ref8) => { | ||
const wrapper = _ref8 => { | ||
let { | ||
@@ -319,3 +301,2 @@ children | ||
}; | ||
const { | ||
@@ -350,4 +331,3 @@ result | ||
}; | ||
const wrapper = (_ref9) => { | ||
const wrapper = _ref9 => { | ||
let { | ||
@@ -360,6 +340,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
result | ||
} = renderHook(() => useDataMutation(mutation), { | ||
@@ -366,0 +344,0 @@ wrapper |
@@ -6,3 +6,2 @@ import { useState, useRef, useCallback, useDebugValue } from 'react'; | ||
import { useStaticInput } from './useStaticInput'; | ||
const noop = () => { | ||
@@ -15,3 +14,2 @@ /** | ||
}; | ||
setLogger({ | ||
@@ -40,2 +38,3 @@ log: noop, | ||
}); | ||
/** | ||
@@ -50,2 +49,3 @@ * Display current query state and refetch count in React DevTools | ||
}, debugValue => JSON.stringify(debugValue)); | ||
/** | ||
@@ -57,6 +57,4 @@ * User callbacks and refetch handling | ||
var _queryState$current$r, _queryState$current; | ||
(_queryState$current$r = (_queryState$current = queryState.current).refetchCallback) === null || _queryState$current$r === void 0 ? void 0 : _queryState$current$r.call(_queryState$current, data); | ||
queryState.current.refetchCallback = undefined; | ||
if (userOnSuccess) { | ||
@@ -66,7 +64,5 @@ userOnSuccess(data); | ||
}; | ||
const onError = error => { | ||
// If we'd want to reject on errors we'd call the cb with the error here | ||
queryState.current.refetchCallback = undefined; | ||
if (userOnError) { | ||
@@ -76,2 +72,3 @@ userOnError(error); | ||
}; | ||
/** | ||
@@ -81,10 +78,7 @@ * Setting up react-query | ||
const engine = useDataEngine(); | ||
const queryKey = [staticQuery, queryState.current.variables]; | ||
const queryFn = () => engine.query(staticQuery, { | ||
variables: queryState.current.variables | ||
}); | ||
const { | ||
@@ -102,2 +96,3 @@ isIdle, | ||
}); | ||
/** | ||
@@ -118,2 +113,3 @@ * Refetch allows a user to update the variables or just | ||
} = mergeAndCompareVariables(queryState.current.variables, newVariables, queryState.current.variablesHash); | ||
/** | ||
@@ -123,3 +119,2 @@ * If there are no updates that will trigger an automatic refetch | ||
*/ | ||
if (queryState.current.enabled && identical) { | ||
@@ -129,3 +124,3 @@ return queryRefetch({ | ||
throwOnError: false | ||
}).then((_ref) => { | ||
}).then(_ref => { | ||
let { | ||
@@ -137,7 +132,7 @@ data | ||
} | ||
queryState.current.variables = mergedVariables; | ||
queryState.current.variablesHash = mergedVariablesHash; | ||
queryState.current.enabled = true; // This promise does not currently reject on errors | ||
queryState.current.enabled = true; | ||
// This promise does not currently reject on errors | ||
const refetchPromise = new Promise(resolve => { | ||
@@ -147,7 +142,9 @@ queryState.current.refetchCallback = data => { | ||
}; | ||
}); // Trigger a react-query refetch by incrementing variablesUpdateCount state | ||
}); | ||
// Trigger a react-query refetch by incrementing variablesUpdateCount state | ||
setVariablesUpdateCount(prevCount => prevCount + 1); | ||
return refetchPromise; | ||
}, [queryRefetch]); | ||
/** | ||
@@ -157,3 +154,2 @@ * react-query returns null or an error, but we return undefined | ||
*/ | ||
const ourError = error || undefined; | ||
@@ -160,0 +156,0 @@ return { |
@@ -1,2 +0,2 @@ | ||
import { renderHook, act } from '@testing-library/react-hooks'; | ||
import { renderHook, waitFor, act } from '@testing-library/react'; | ||
import * as React from 'react'; | ||
@@ -16,4 +16,3 @@ import { CustomDataProvider } from '../components/CustomDataProvider'; | ||
}; | ||
const wrapper = (_ref) => { | ||
const wrapper = _ref => { | ||
let { | ||
@@ -26,8 +25,6 @@ children | ||
}; | ||
const onComplete = jest.fn(); | ||
const onError = jest.fn(); | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query, { | ||
@@ -44,11 +41,12 @@ lazy: false, | ||
}); | ||
await waitForNextUpdate(); | ||
expect(onComplete).toHaveBeenCalledWith({ | ||
x: 42 | ||
}); | ||
expect(onError).not.toHaveBeenCalled(); | ||
expect(result.current).toMatchObject({ | ||
data: { | ||
await waitFor(() => { | ||
expect(onComplete).toHaveBeenCalledWith({ | ||
x: 42 | ||
} | ||
}); | ||
expect(onError).not.toHaveBeenCalled(); | ||
expect(result.current).toMatchObject({ | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
@@ -70,4 +68,3 @@ }); | ||
}; | ||
const wrapper = (_ref2) => { | ||
const wrapper = _ref2 => { | ||
let { | ||
@@ -80,8 +77,6 @@ children | ||
}; | ||
const onComplete = jest.fn(); | ||
const onError = jest.fn(); | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query, { | ||
@@ -97,7 +92,8 @@ onError, | ||
}); | ||
await waitForNextUpdate(); | ||
expect(onError).toHaveBeenCalledWith(expectedError); | ||
expect(onComplete).not.toHaveBeenCalled(); | ||
expect(result.current).toMatchObject({ | ||
error: expectedError | ||
await waitFor(() => { | ||
expect(onError).toHaveBeenCalledWith(expectedError); | ||
expect(onComplete).not.toHaveBeenCalled(); | ||
expect(result.current).toMatchObject({ | ||
error: expectedError | ||
}); | ||
}); | ||
@@ -115,3 +111,3 @@ }); | ||
resource: 'answer', | ||
id: (_ref3) => { | ||
id: _ref3 => { | ||
let { | ||
@@ -128,7 +124,5 @@ id | ||
} = _ref4; | ||
switch (id) { | ||
case one: | ||
return Promise.resolve(resultOne); | ||
case two: | ||
@@ -141,4 +135,3 @@ return Promise.resolve(resultTwo); | ||
}; | ||
const wrapper = (_ref5) => { | ||
const wrapper = _ref5 => { | ||
let { | ||
@@ -151,3 +144,2 @@ children | ||
}; | ||
const initialProps = { | ||
@@ -163,3 +155,2 @@ query, | ||
result, | ||
waitForNextUpdate, | ||
rerender | ||
@@ -175,7 +166,8 @@ } = renderHook(props => useDataQuery(props.query, props.options), { | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
data: { | ||
x: resultOne | ||
} | ||
await waitFor(() => { | ||
expect(result.current).toMatchObject({ | ||
data: { | ||
x: resultOne | ||
} | ||
}); | ||
}); | ||
@@ -212,4 +204,3 @@ act(() => { | ||
}; | ||
const wrapper = (_ref6) => { | ||
const wrapper = _ref6 => { | ||
let { | ||
@@ -222,6 +213,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query), { | ||
@@ -234,10 +223,11 @@ wrapper | ||
}); | ||
await waitForNextUpdate(); | ||
expect(mockSpy).toHaveBeenCalledTimes(1); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
await waitFor(() => { | ||
expect(mockSpy).toHaveBeenCalledTimes(1); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
@@ -266,4 +256,3 @@ }); | ||
}; | ||
const wrapper = (_ref7) => { | ||
const wrapper = _ref7 => { | ||
let { | ||
@@ -277,6 +266,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query), { | ||
@@ -290,10 +277,11 @@ wrapper | ||
}); | ||
await waitForNextUpdate(); // Now the cache will contain a value for 'answer' without variables | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
await waitFor(() => { | ||
// Now the cache will contain a value for 'answer' without variables | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
@@ -310,9 +298,10 @@ act(() => { | ||
}); | ||
await waitForNextUpdate(); // Now the cache will contain a value for 'answer' with and without variables | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
data: { | ||
x: 43 | ||
} | ||
await waitFor(() => { | ||
// Now the cache will contain a value for 'answer' with and without variables | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
data: { | ||
x: 43 | ||
} | ||
}); | ||
}); | ||
@@ -324,4 +313,5 @@ act(() => { | ||
}); | ||
}); // This should return the resource from the cache without fetching | ||
}); | ||
// This should return the resource from the cache without fetching | ||
expect(mockSpy).toHaveBeenCalledTimes(2); | ||
@@ -348,4 +338,3 @@ expect(result.current).toMatchObject({ | ||
}; | ||
const wrapper = (_ref8) => { | ||
const wrapper = _ref8 => { | ||
let { | ||
@@ -358,6 +347,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => { | ||
@@ -377,12 +364,13 @@ const one = useDataQuery(query); | ||
expect(result.current).toMatchObject([loading, loading, loading]); | ||
await waitForNextUpdate(); | ||
const done = { | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}; | ||
expect(mockSpy).toHaveBeenCalledTimes(1); | ||
expect(result.current).toMatchObject([done, done, done]); | ||
await waitFor(() => { | ||
const done = { | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}; | ||
expect(mockSpy).toHaveBeenCalledTimes(1); | ||
expect(result.current).toMatchObject([done, done, done]); | ||
}); | ||
}); | ||
@@ -400,4 +388,3 @@ }); | ||
}; | ||
const wrapper = (_ref9) => { | ||
const wrapper = _ref9 => { | ||
let { | ||
@@ -410,6 +397,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query), { | ||
@@ -422,9 +407,10 @@ wrapper | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
await waitFor(() => { | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
@@ -445,4 +431,3 @@ }); | ||
}; | ||
const wrapper = (_ref10) => { | ||
const wrapper = _ref10 => { | ||
let { | ||
@@ -455,6 +440,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query), { | ||
@@ -467,10 +450,11 @@ wrapper | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42, | ||
y: 24 | ||
} | ||
await waitFor(() => { | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42, | ||
y: 24 | ||
} | ||
}); | ||
}); | ||
@@ -492,4 +476,3 @@ }); | ||
}; | ||
const wrapper = (_ref11) => { | ||
const wrapper = _ref11 => { | ||
let { | ||
@@ -502,6 +485,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query), { | ||
@@ -514,7 +495,8 @@ wrapper | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
error: expectedError | ||
await waitFor(() => { | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
error: expectedError | ||
}); | ||
}); | ||
@@ -538,4 +520,3 @@ }); | ||
}; | ||
const wrapper = (_ref12) => { | ||
const wrapper = _ref12 => { | ||
let { | ||
@@ -548,6 +529,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query), { | ||
@@ -560,7 +539,8 @@ wrapper | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
error: expectedError | ||
await waitFor(() => { | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
error: expectedError | ||
}); | ||
}); | ||
@@ -584,4 +564,3 @@ }); | ||
}; | ||
const wrapper = (_ref13) => { | ||
const wrapper = _ref13 => { | ||
let { | ||
@@ -594,6 +573,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
result | ||
} = renderHook(() => useDataQuery(query, { | ||
@@ -639,3 +616,2 @@ lazy: true | ||
} | ||
return 0; | ||
@@ -649,3 +625,3 @@ }); | ||
resource: 'answer', | ||
id: (_ref14) => { | ||
id: _ref14 => { | ||
let { | ||
@@ -658,4 +634,3 @@ id | ||
}; | ||
const wrapper = (_ref15) => { | ||
const wrapper = _ref15 => { | ||
let { | ||
@@ -668,6 +643,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
result | ||
} = renderHook(() => useDataQuery(query, { | ||
@@ -700,3 +673,2 @@ lazy: true | ||
} | ||
return 0; | ||
@@ -710,3 +682,3 @@ }); | ||
resource: 'answer', | ||
id: (_ref16) => { | ||
id: _ref16 => { | ||
let { | ||
@@ -719,4 +691,3 @@ id | ||
}; | ||
const wrapper = (_ref17) => { | ||
const wrapper = _ref17 => { | ||
let { | ||
@@ -729,6 +700,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitFor | ||
result | ||
} = renderHook(() => useDataQuery(query, { | ||
@@ -768,4 +737,3 @@ lazy: true, | ||
}; | ||
const wrapper = (_ref18) => { | ||
const wrapper = _ref18 => { | ||
let { | ||
@@ -778,6 +746,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate, | ||
rerender | ||
@@ -788,5 +754,8 @@ } = renderHook(() => useDataQuery(query), { | ||
const firstRefetch = result.current.refetch; | ||
await waitForNextUpdate(); | ||
// await waitFor(() => {}) | ||
act(() => { | ||
result.current.refetch(); | ||
/** | ||
@@ -797,7 +766,7 @@ * FIXME: https://github.com/tannerlinsley/react-query/issues/2481 | ||
*/ | ||
rerender(); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current.refetch).toBe(firstRefetch); | ||
await waitFor(() => { | ||
expect(result.current.refetch).toBe(firstRefetch); | ||
}); | ||
}); | ||
@@ -815,4 +784,3 @@ it('Should return stale data and set loading to true on refetch', async () => { | ||
}; | ||
const wrapper = (_ref19) => { | ||
const wrapper = _ref19 => { | ||
let { | ||
@@ -825,6 +793,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate, | ||
rerender | ||
@@ -839,12 +805,14 @@ } = renderHook(() => useDataQuery(query), { | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
await waitFor(() => { | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
act(() => { | ||
result.current.refetch(); | ||
/** | ||
@@ -855,3 +823,2 @@ * FIXME: https://github.com/tannerlinsley/react-query/issues/2481 | ||
*/ | ||
rerender(); | ||
@@ -868,11 +835,12 @@ }); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(mockSpy).toHaveBeenCalledTimes(2); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
fetching: false, | ||
called: true, | ||
data: { | ||
x: 43 | ||
} | ||
await waitFor(() => { | ||
expect(mockSpy).toHaveBeenCalledTimes(2); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
fetching: false, | ||
called: true, | ||
data: { | ||
x: 43 | ||
} | ||
}); | ||
}); | ||
@@ -890,4 +858,3 @@ }); | ||
}; | ||
const wrapper = (_ref20) => { | ||
const wrapper = _ref20 => { | ||
let { | ||
@@ -900,6 +867,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query, { | ||
@@ -923,9 +888,10 @@ lazy: true | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
await waitFor(() => { | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
@@ -942,4 +908,3 @@ }); | ||
}; | ||
const wrapper = (_ref21) => { | ||
const wrapper = _ref21 => { | ||
let { | ||
@@ -952,8 +917,6 @@ children | ||
}; | ||
const onComplete = jest.fn(); | ||
const onError = jest.fn(); | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query, { | ||
@@ -969,14 +932,15 @@ lazy: true, | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
await waitFor(() => { | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
expect(onComplete).toHaveBeenCalledWith({ | ||
x: 42 | ||
} | ||
}); | ||
expect(onError).not.toHaveBeenCalled(); | ||
}); | ||
expect(onComplete).toHaveBeenCalledWith({ | ||
x: 42 | ||
}); | ||
expect(onError).not.toHaveBeenCalled(); | ||
}); | ||
@@ -995,4 +959,3 @@ it('Should call onError after a failed refetch', async () => { | ||
}; | ||
const wrapper = (_ref22) => { | ||
const wrapper = _ref22 => { | ||
let { | ||
@@ -1005,8 +968,6 @@ children | ||
}; | ||
const onComplete = jest.fn(); | ||
const onError = jest.fn(); | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query, { | ||
@@ -1022,7 +983,8 @@ lazy: true, | ||
}); | ||
await waitForNextUpdate(); | ||
expect(onError).toHaveBeenCalledWith(expectedError); | ||
expect(onComplete).not.toHaveBeenCalled(); | ||
expect(result.current).toMatchObject({ | ||
error: expectedError | ||
await waitFor(() => { | ||
expect(onError).toHaveBeenCalledWith(expectedError); | ||
expect(onComplete).not.toHaveBeenCalled(); | ||
expect(result.current).toMatchObject({ | ||
error: expectedError | ||
}); | ||
}); | ||
@@ -1039,3 +1001,3 @@ }); | ||
resource: 'answer', | ||
params: (_ref23) => { | ||
params: _ref23 => { | ||
let { | ||
@@ -1058,4 +1020,3 @@ one, | ||
}; | ||
const wrapper = (_ref24) => { | ||
const wrapper = _ref24 => { | ||
let { | ||
@@ -1068,6 +1029,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query, { | ||
@@ -1078,10 +1037,11 @@ variables | ||
}); | ||
await waitForNextUpdate(); | ||
expect(spy).toHaveBeenCalledTimes(1); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
await waitFor(() => { | ||
expect(spy).toHaveBeenCalledTimes(1); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
@@ -1091,10 +1051,11 @@ act(() => { | ||
}); | ||
await waitForNextUpdate(); | ||
expect(spy).toHaveBeenCalledTimes(2); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
await waitFor(() => { | ||
expect(spy).toHaveBeenCalledTimes(2); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
@@ -1111,4 +1072,3 @@ }); | ||
}; | ||
const wrapper = (_ref25) => { | ||
const wrapper = _ref25 => { | ||
let { | ||
@@ -1121,6 +1081,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query, { | ||
@@ -1136,12 +1094,13 @@ lazy: true | ||
}); | ||
await waitForNextUpdate(); | ||
expect(ourPromise).resolves.toEqual({ | ||
x: 42 | ||
}); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
await waitFor(() => { | ||
expect(ourPromise).resolves.toEqual({ | ||
x: 42 | ||
} | ||
}); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
@@ -1158,4 +1117,3 @@ }); | ||
}; | ||
const wrapper = (_ref26) => { | ||
const wrapper = _ref26 => { | ||
let { | ||
@@ -1168,6 +1126,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query, { | ||
@@ -1183,12 +1139,13 @@ lazy: false | ||
}); | ||
await waitForNextUpdate(); | ||
expect(reactQueryPromise).resolves.toEqual({ | ||
x: 42 | ||
}); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
await waitFor(() => { | ||
expect(reactQueryPromise).resolves.toEqual({ | ||
x: 42 | ||
} | ||
}); | ||
expect(result.current).toMatchObject({ | ||
loading: false, | ||
called: true, | ||
data: { | ||
x: 42 | ||
} | ||
}); | ||
}); | ||
@@ -1208,4 +1165,3 @@ }); | ||
}; | ||
const wrapper = (_ref27) => { | ||
const wrapper = _ref27 => { | ||
let { | ||
@@ -1218,6 +1174,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query, { | ||
@@ -1233,6 +1187,7 @@ lazy: true | ||
}); | ||
await waitForNextUpdate(); | ||
expect(ourPromise).resolves.toBeUndefined(); | ||
expect(result.current).toMatchObject({ | ||
error: expectedError | ||
await waitFor(() => { | ||
expect(ourPromise).resolves.toBeUndefined(); | ||
expect(result.current).toMatchObject({ | ||
error: expectedError | ||
}); | ||
}); | ||
@@ -1252,4 +1207,3 @@ }); | ||
}; | ||
const wrapper = (_ref28) => { | ||
const wrapper = _ref28 => { | ||
let { | ||
@@ -1262,6 +1216,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query, { | ||
@@ -1277,6 +1229,7 @@ lazy: false | ||
}); | ||
await waitForNextUpdate(); | ||
expect(reactQueryPromise).resolves.toBeUndefined(); | ||
expect(result.current).toMatchObject({ | ||
error: expectedError | ||
await waitFor(() => { | ||
expect(reactQueryPromise).resolves.toBeUndefined(); | ||
expect(result.current).toMatchObject({ | ||
error: expectedError | ||
}); | ||
}); | ||
@@ -1292,3 +1245,3 @@ }); | ||
resource: 'answer', | ||
id: (_ref29) => { | ||
id: _ref29 => { | ||
let { | ||
@@ -1305,7 +1258,5 @@ id | ||
} = _ref30; | ||
switch (id) { | ||
case one: | ||
return Promise.resolve(resultOne); | ||
case two: | ||
@@ -1318,4 +1269,3 @@ return Promise.resolve(resultTwo); | ||
}; | ||
const wrapper = (_ref31) => { | ||
const wrapper = _ref31 => { | ||
let { | ||
@@ -1328,3 +1278,2 @@ children | ||
}; | ||
const initialProps = { | ||
@@ -1339,4 +1288,3 @@ query, | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(props => useDataQuery(props.query, props.options), { | ||
@@ -1346,7 +1294,8 @@ wrapper, | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
data: { | ||
x: resultOne | ||
} | ||
await waitFor(() => { | ||
expect(result.current).toMatchObject({ | ||
data: { | ||
x: resultOne | ||
} | ||
}); | ||
}); | ||
@@ -1358,8 +1307,9 @@ act(() => { | ||
}); | ||
await waitForNextUpdate(); | ||
expect(mockSpy).toHaveBeenCalledTimes(2); | ||
expect(result.current).toMatchObject({ | ||
data: { | ||
x: resultTwo | ||
} | ||
await waitFor(() => { | ||
expect(mockSpy).toHaveBeenCalledTimes(2); | ||
expect(result.current).toMatchObject({ | ||
data: { | ||
x: resultTwo | ||
} | ||
}); | ||
}); | ||
@@ -1380,3 +1330,3 @@ }); | ||
resource: 'answer', | ||
params: (_ref32) => { | ||
params: _ref32 => { | ||
let { | ||
@@ -1399,4 +1349,3 @@ one, | ||
}; | ||
const wrapper = (_ref33) => { | ||
const wrapper = _ref33 => { | ||
let { | ||
@@ -1409,6 +1358,4 @@ children | ||
}; | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useDataQuery(query, { | ||
@@ -1419,17 +1366,20 @@ variables: initialVariables | ||
}); | ||
await waitForNextUpdate(); | ||
expect(mockSpy).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ | ||
params: initialVariables | ||
}), expect.anything()); | ||
await waitFor(() => { | ||
expect(mockSpy).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ | ||
params: initialVariables | ||
}), expect.anything()); | ||
}); | ||
act(() => { | ||
result.current.refetch(newVariables); | ||
}); | ||
await waitForNextUpdate(); | ||
expect(mockSpy).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ | ||
params: { ...initialVariables, | ||
...newVariables | ||
} | ||
}), expect.anything()); | ||
await waitFor(() => { | ||
expect(mockSpy).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ | ||
params: { | ||
...initialVariables, | ||
...newVariables | ||
} | ||
}), expect.anything()); | ||
}); | ||
}); | ||
}); | ||
}); |
import { useState, useCallback, useRef, useEffect } from 'react'; | ||
import { FetchError } from '../../engine'; | ||
import { useStaticInput } from './useStaticInput'; | ||
export const useQueryExecutor = (_ref) => { | ||
export const useQueryExecutor = _ref => { | ||
let { | ||
@@ -41,10 +41,9 @@ execute, | ||
} : state); | ||
if (singular) { | ||
abort(); // Cleanup any in-progress fetches | ||
} | ||
const controller = new AbortController(); | ||
abortControllersRef.current.push(controller); | ||
variables.current = { ...variables.current, | ||
variables.current = { | ||
...variables.current, | ||
...newVariables | ||
@@ -67,3 +66,2 @@ }; | ||
} | ||
return new Promise(() => undefined); // Wait forever | ||
@@ -78,8 +76,8 @@ }).catch(error => { | ||
} | ||
return new Promise(() => undefined); // Don't throw errors in refetch promises, wait forever | ||
}); | ||
}, [abort, onComplete, onError, singular, theExecute]); // Don't include immediate or refetch as deps, otherwise unintentional refetches | ||
}, [abort, onComplete, onError, singular, theExecute]); | ||
// Don't include immediate or refetch as deps, otherwise unintentional refetches | ||
// may be triggered by changes to input, i.e. recreating the onComplete callback | ||
useEffect(() => { | ||
@@ -89,3 +87,2 @@ if (immediate) { | ||
} | ||
return abort; | ||
@@ -92,0 +89,0 @@ }, []); // eslint-disable-line react-hooks/exhaustive-deps |
@@ -1,6 +0,6 @@ | ||
import { renderHook, act } from '@testing-library/react-hooks'; | ||
import { renderHook, act, waitFor } from '@testing-library/react'; | ||
import { useQueryExecutor } from './useQueryExecutor'; | ||
const testError = new Error('TEST ERROR'); | ||
let theSignal; | ||
const execute = jest.fn(async (_ref) => { | ||
const execute = jest.fn(async _ref => { | ||
let { | ||
@@ -36,4 +36,3 @@ signal | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useQueryExecutor({ | ||
@@ -49,7 +48,8 @@ execute, | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
called: true, | ||
loading: false, | ||
data: 42 | ||
await waitFor(() => { | ||
expect(result.current).toMatchObject({ | ||
called: true, | ||
loading: false, | ||
data: 42 | ||
}); | ||
}); | ||
@@ -59,4 +59,3 @@ }); | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useQueryExecutor({ | ||
@@ -79,7 +78,8 @@ execute, | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
called: true, | ||
loading: false, | ||
data: 42 | ||
await waitFor(() => { | ||
expect(result.current).toMatchObject({ | ||
called: true, | ||
loading: false, | ||
data: 42 | ||
}); | ||
}); | ||
@@ -89,4 +89,3 @@ }); | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useQueryExecutor({ | ||
@@ -109,7 +108,8 @@ execute: failingExecute, | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
called: true, | ||
loading: false, | ||
error: testError | ||
await waitFor(() => { | ||
expect(result.current).toMatchObject({ | ||
called: true, | ||
loading: false, | ||
error: testError | ||
}); | ||
}); | ||
@@ -120,5 +120,4 @@ }); | ||
result, | ||
waitForNextUpdate, | ||
rerender | ||
} = renderHook((_ref2) => { | ||
} = renderHook(_ref2 => { | ||
let { | ||
@@ -146,15 +145,15 @@ onComplete | ||
}); | ||
await waitForNextUpdate(); | ||
expect(result.current).toMatchObject({ | ||
called: true, | ||
loading: false, | ||
data: 42 | ||
await waitFor(() => { | ||
expect(result.current).toMatchObject({ | ||
called: true, | ||
loading: false, | ||
data: 42 | ||
}); | ||
expect(theSignal && theSignal.aborted).toBe(false); | ||
expect(execute).toHaveBeenCalledTimes(1); | ||
}); | ||
expect(theSignal && theSignal.aborted).toBe(false); | ||
expect(execute).toHaveBeenCalledTimes(1); | ||
}); | ||
it('Should respect abort signal', async () => { | ||
const { | ||
result, | ||
waitForNextUpdate | ||
result | ||
} = renderHook(() => useQueryExecutor({ | ||
@@ -161,0 +160,0 @@ execute, |
@@ -1,2 +0,2 @@ | ||
import { renderHook, act } from '@testing-library/react-hooks'; | ||
import { renderHook, act } from '@testing-library/react'; | ||
import { useStaticInput } from './useStaticInput'; | ||
@@ -22,3 +22,3 @@ describe('useStaticInput', () => { | ||
rerender | ||
} = renderHook((_ref) => { | ||
} = renderHook(_ref => { | ||
let { | ||
@@ -44,3 +44,3 @@ value | ||
rerender | ||
} = renderHook((_ref2) => { | ||
} = renderHook(_ref2 => { | ||
let { | ||
@@ -73,3 +73,3 @@ value | ||
rerender | ||
} = renderHook((_ref3) => { | ||
} = renderHook(_ref3 => { | ||
let { | ||
@@ -99,3 +99,3 @@ value | ||
rerender | ||
} = renderHook((_ref4) => { | ||
} = renderHook(_ref4 => { | ||
let { | ||
@@ -136,3 +136,3 @@ value | ||
rerender | ||
} = renderHook((_ref5) => { | ||
} = renderHook(_ref5 => { | ||
let { | ||
@@ -139,0 +139,0 @@ value |
@@ -1,4 +0,4 @@ | ||
import '@testing-library/jest-dom/extend-expect'; | ||
import '@testing-library/jest-dom'; | ||
process.on('unhandledRejection', err => { | ||
throw err; | ||
}); |
import { FetchError } from './FetchError'; | ||
import { QueryVariables } from './Query'; | ||
export declare type FetchType = 'create' | 'read' | 'update' | 'json-patch' | 'replace' | 'delete'; | ||
export type FetchType = 'create' | 'read' | 'update' | 'json-patch' | 'replace' | 'delete'; | ||
export interface QueryExecuteOptions { | ||
@@ -5,0 +5,0 @@ variables?: QueryVariables; |
@@ -1,3 +0,3 @@ | ||
export declare type FetchErrorTypeName = 'network' | 'unknown' | 'access' | 'aborted'; | ||
export declare type FetchErrorDetails = { | ||
export type FetchErrorTypeName = 'network' | 'unknown' | 'access' | 'aborted'; | ||
export type FetchErrorDetails = { | ||
httpStatus?: string; | ||
@@ -4,0 +4,0 @@ httpStatusCode?: number; |
@@ -1,2 +0,2 @@ | ||
export declare type JsonValue = boolean | number | string | null | JsonArray | JsonMap; | ||
export type JsonValue = boolean | number | string | null | JsonArray | JsonMap; | ||
export interface JsonMap { | ||
@@ -3,0 +3,0 @@ [key: string]: JsonValue; |
import { FetchError } from './FetchError'; | ||
import { ResourceQuery, QueryVariables } from './Query'; | ||
export declare type MutationType = 'create' | 'update' | 'json-patch' | 'replace' | 'delete'; | ||
export type MutationType = 'create' | 'update' | 'json-patch' | 'replace' | 'delete'; | ||
export interface MutationData { | ||
@@ -24,3 +24,3 @@ [key: string]: any; | ||
} | ||
export declare type Mutation = CreateMutation | UpdateMutation | DeleteMutation; | ||
export type Mutation = CreateMutation | UpdateMutation | DeleteMutation; | ||
export interface MutationOptions { | ||
@@ -27,0 +27,0 @@ variables?: QueryVariables; |
@@ -1,1 +0,1 @@ | ||
export declare type PossiblyDynamic<Type, InputType> = Type | ((input: InputType) => Type); | ||
export type PossiblyDynamic<Type, InputType> = Type | ((input: InputType) => Type); |
@@ -5,3 +5,3 @@ import { FetchError } from './FetchError'; | ||
import { QueryParameters } from './QueryParameters'; | ||
export declare type QueryVariables = Record<string, any>; | ||
export type QueryVariables = Record<string, any>; | ||
export interface ResourceQuery { | ||
@@ -18,4 +18,4 @@ resource: string; | ||
} | ||
export declare type Query = Record<string, ResourceQuery>; | ||
export declare type QueryResult = JsonMap; | ||
export type Query = Record<string, ResourceQuery>; | ||
export type QueryResult = JsonMap; | ||
export interface QueryOptions<TQueryResult = QueryResult> { | ||
@@ -22,0 +22,0 @@ variables?: QueryVariables; |
@@ -1,8 +0,8 @@ | ||
declare type QueryParameterSingularValue = string | number | boolean; | ||
type QueryParameterSingularValue = string | number | boolean; | ||
interface QueryParameterAliasedValue { | ||
[name: string]: QueryParameterSingularValue; | ||
} | ||
declare type QueryParameterSingularOrAliasedValue = QueryParameterSingularValue | QueryParameterAliasedValue; | ||
declare type QueryParameterMultipleValue = QueryParameterSingularOrAliasedValue[]; | ||
export declare type QueryParameterValue = QueryParameterSingularValue | QueryParameterAliasedValue | QueryParameterMultipleValue | undefined; | ||
type QueryParameterSingularOrAliasedValue = QueryParameterSingularValue | QueryParameterAliasedValue; | ||
type QueryParameterMultipleValue = QueryParameterSingularOrAliasedValue[]; | ||
export type QueryParameterValue = QueryParameterSingularValue | QueryParameterAliasedValue | QueryParameterMultipleValue | undefined; | ||
export interface QueryParameters { | ||
@@ -9,0 +9,0 @@ pageSize?: number; |
import { DataEngineLink, DataEngineLinkExecuteOptions, FetchType, JsonValue, ResolvedResourceQuery } from '../engine'; | ||
export declare type CustomResourceFactory = (type: FetchType, query: ResolvedResourceQuery, options?: DataEngineLinkExecuteOptions) => Promise<JsonValue | undefined>; | ||
export declare type CustomResource = JsonValue | CustomResourceFactory; | ||
export type CustomResourceFactory = (type: FetchType, query: ResolvedResourceQuery, options?: DataEngineLinkExecuteOptions) => Promise<JsonValue | undefined>; | ||
export type CustomResource = JsonValue | CustomResourceFactory; | ||
export interface CustomData { | ||
@@ -5,0 +5,0 @@ [resourceName: string]: CustomResource; |
import { ResolvedResourceQuery, FetchType } from '../../engine'; | ||
export declare const queryToRequestOptions: (type: FetchType, query: ResolvedResourceQuery, signal?: AbortSignal | undefined) => RequestInit; | ||
export declare const queryToRequestOptions: (type: FetchType, query: ResolvedResourceQuery, signal?: AbortSignal) => RequestInit; |
import { ResolvedResourceQuery, FetchType } from '../../../engine'; | ||
declare type RequestContentType = 'application/json' | 'application/json-patch+json' | 'text/plain' | 'multipart/form-data' | 'application/x-www-form-urlencoded' | null; | ||
type RequestContentType = 'application/json' | 'application/json-patch+json' | 'text/plain' | 'multipart/form-data' | 'application/x-www-form-urlencoded' | null; | ||
export declare const requestContentType: (type: FetchType, query: ResolvedResourceQuery) => null | RequestContentType; | ||
@@ -4,0 +4,0 @@ export declare const requestHeadersForContentType: (contentType: RequestContentType) => undefined | Record<'Content-Type', string>; |
import type { QueryVariables } from '../../engine'; | ||
export declare const mergeAndCompareVariables: (previousVariables?: QueryVariables | undefined, newVariables?: QueryVariables | undefined, previousHash?: string | undefined) => { | ||
export declare const mergeAndCompareVariables: (previousVariables?: QueryVariables, newVariables?: QueryVariables, previousHash?: string) => { | ||
identical: boolean; | ||
@@ -4,0 +4,0 @@ mergedVariablesHash: string | undefined; |
@@ -13,7 +13,7 @@ import DataEngine from './engine/DataEngine'; | ||
} | ||
export declare type RefetchOptions = QueryVariables; | ||
export declare type RefetchFunction<ReturnType> = (options?: RefetchOptions) => Promise<ReturnType>; | ||
export declare type QueryRefetchFunction = RefetchFunction<QueryResult>; | ||
export declare type MutationFunction = RefetchFunction<JsonValue>; | ||
export declare type ExecuteFunction<T> = (options: QueryExecuteOptions) => Promise<T>; | ||
export type RefetchOptions = QueryVariables; | ||
export type RefetchFunction<ReturnType> = (options?: RefetchOptions) => Promise<ReturnType>; | ||
export type QueryRefetchFunction = RefetchFunction<QueryResult>; | ||
export type MutationFunction = RefetchFunction<JsonValue>; | ||
export type ExecuteFunction<T> = (options: QueryExecuteOptions) => Promise<T>; | ||
export interface ExecuteHookInput<ReturnType> { | ||
@@ -54,2 +54,2 @@ execute: ExecuteFunction<ReturnType>; | ||
} | ||
export declare type MutationRenderInput = [MutationFunction, MutationState]; | ||
export type MutationRenderInput = [MutationFunction, MutationState]; |
{ | ||
"name": "@dhis2/app-service-data", | ||
"version": "3.11.3", | ||
"version": "3.12.0-alpha.1", | ||
"main": "./build/cjs/index.js", | ||
@@ -38,7 +38,7 @@ "module": "./build/es/index.js", | ||
"peerDependencies": { | ||
"@dhis2/app-service-config": "3.11.3", | ||
"@dhis2/app-service-config": "3.12.0-alpha.1", | ||
"prop-types": "^15.7.2", | ||
"react": "^16.8", | ||
"react-dom": "^16.8" | ||
"react": "^16.8 || ^18", | ||
"react-dom": "^16.8 || ^18" | ||
} | ||
} |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
353494
10863
2