UNPKG

@opendatasoft/api-client

Version:
1,180 lines (1,172 loc) 41.8 kB
import update from 'immutability-helper'; function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function () { return !!t; })(); } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _regeneratorRuntime() { _regeneratorRuntime = function () { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function (t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function (t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(typeof e + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function (e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function () { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function (e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function (t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function (t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function (t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function (t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function (e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } 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); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _isNativeFunction(fn) { try { return Function.toString.call(fn).indexOf("[native code]") !== -1; } catch (e) { return typeof fn === "function"; } } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } // Predefined error /* eslint-disable max-classes-per-file */ var ApiError = /*#__PURE__*/function (_Error) { _inherits(ApiError, _Error); // eslint-disable-next-line @typescript-eslint/no-explicit-any function ApiError(response, details) { var _this; _classCallCheck(this, ApiError); var proto = (this instanceof ApiError ? this.constructor : void 0).prototype; _this = _callSuper(this, ApiError, [JSON.stringify(details)]); _this.details = details; _this.response = response; Object.setPrototypeOf(_assertThisInitialized(_this), proto); return _this; } return _createClass(ApiError); }( /*#__PURE__*/_wrapNativeSuper(Error)); var UserError = /*#__PURE__*/function (_ApiError) { _inherits(UserError, _ApiError); function UserError() { _classCallCheck(this, UserError); return _callSuper(this, UserError, arguments); } return _createClass(UserError); }(ApiError); var AuthenticationError = /*#__PURE__*/function (_UserError) { _inherits(AuthenticationError, _UserError); function AuthenticationError() { _classCallCheck(this, AuthenticationError); return _callSuper(this, AuthenticationError, arguments); } return _createClass(AuthenticationError); }(UserError); var NotFoundError = /*#__PURE__*/function (_UserError2) { _inherits(NotFoundError, _UserError2); function NotFoundError() { _classCallCheck(this, NotFoundError); return _callSuper(this, NotFoundError, arguments); } return _createClass(NotFoundError); }(UserError); var ServerError = /*#__PURE__*/function (_ApiError2) { _inherits(ServerError, _ApiError2); function ServerError() { _classCallCheck(this, ServerError); return _callSuper(this, ServerError, arguments); } return _createClass(ServerError); }(ApiError); var API_KEY_AUTH_TYPE = 'ApiKey'; // Using the UMD bundle in ObservableHQ, the error "ReferenceError: global is not defined" is returned. // ... I'm not sure why it behaves that way, but this fixes the issue: // eslint-disable-next-line no-underscore-dangle, @typescript-eslint/naming-convention, @typescript-eslint/no-explicit-any var _global = typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : {}; function computeBaseUrl(domain) { var baseUrl; if (domain.startsWith('http://') || domain.startsWith('https://')) { baseUrl = domain; } else { baseUrl = "https://".concat(domain, ".opendatasoft.com"); } if (!baseUrl.endsWith('/')) { baseUrl += '/'; } baseUrl += 'api/explore/v2.1/'; return baseUrl; } function buildConfig(apiClientOptions, defaultConfig) { if (!apiClientOptions) { return defaultConfig; } var domain = apiClientOptions.domain, fetch = apiClientOptions.fetch, apiKey = apiClientOptions.apiKey, headers = apiClientOptions.headers, interceptRequest = apiClientOptions.interceptRequest, interceptResponse = apiClientOptions.interceptResponse, hideDeprecatedWarning = apiClientOptions.hideDeprecatedWarning; var newConfig = {}; if (domain) newConfig.baseUrl = computeBaseUrl(domain); if (apiKey) newConfig.apiKey = apiKey; if (fetch) newConfig.fetch = fetch; if (headers) newConfig.headers = new Headers(headers); if (interceptRequest) newConfig.interceptRequest = interceptRequest; if (interceptResponse) newConfig.interceptResponse = interceptResponse; newConfig.hideDeprecatedWarning = Boolean(hideDeprecatedWarning); return update(defaultConfig, { $merge: newConfig }); } var ApiClient = /*#__PURE__*/function () { /** * Constructs an instance of {@link ApiClient} */ function ApiClient(options) { var _global$location; _classCallCheck(this, ApiClient); this.deprecatedWarningShown = []; var fetch = (options === null || options === void 0 ? void 0 : options.fetch) || (_global === null || _global === void 0 ? void 0 : _global.fetch); if (!fetch) { throw new Error('fetch() was not found, try installing a polyfill in the browser or node-fetch in nodejs. You can pass fetch as an option to the api client.'); } var domain = (options === null || options === void 0 ? void 0 : options.domain) || (_global === null || _global === void 0 || (_global$location = _global.location) === null || _global$location === void 0 ? void 0 : _global$location.origin); if (!domain) { throw new Error('Missing domain'); } this.defaultConfig = buildConfig(options, { baseUrl: computeBaseUrl(domain), fetch: fetch }); } _createClass(ApiClient, [{ key: "get", value: function () { var _get = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(query, options) { var config, path, url, headers, request, fetch, fetchResponse, msg, data, errorData, response; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: config = buildConfig(options, this.defaultConfig); // Build the URL path = typeof query === 'string' ? query : query.toString(); if (path.startsWith('/')) path = path.slice(1); url = new URL(path, config.baseUrl); url.searchParams.sort(); // Url stability is HTTP cache friendly // Build the Headers headers = config.headers || new Headers(); headers.append('Accept', 'application/json'); if (config.apiKey) { headers.append('Authorization', "".concat(API_KEY_AUTH_TYPE, " ").concat(config.apiKey)); } // Build Request request = new Request(url.toString(), { method: 'GET', headers: headers, credentials: 'same-origin' }); if (!config.interceptRequest) { _context.next = 13; break; } _context.next = 12; return config.interceptRequest(request); case 12: request = _context.sent; case 13: // Send request fetch = config.fetch; _context.next = 16; return fetch(request); case 16: fetchResponse = _context.sent; if (!(options !== null && options !== void 0 && options.hideDeprecatedWarning)) { msg = fetchResponse.headers.get('Ods-Explore-Api-Deprecation'); if (msg !== null && !this.deprecatedWarningShown.includes(msg)) { this.deprecatedWarningShown.push(msg); // eslint-disable-next-line no-console console.warn("@opendatasoft/api-client : ".concat(msg)); } } if (!config.interceptResponse) { _context.next = 20; break; } return _context.abrupt("return", config.interceptResponse(fetchResponse)); case 20: if (!fetchResponse.ok) { _context.next = 25; break; } _context.next = 23; return fetchResponse.json(); case 23: data = _context.sent; return _context.abrupt("return", data); case 25: _context.next = 27; return fetchResponse.text(); case 27: response = _context.sent; if (response) { try { errorData = JSON.parse(response); } catch (e) { // Ignore } } if (!errorData && (response || fetchResponse.statusText)) { errorData = { message: response || fetchResponse.statusText }; } if (!(fetchResponse.status === 401)) { _context.next = 32; break; } throw new AuthenticationError(fetchResponse, errorData || 'authentication-error'); case 32: if (!(fetchResponse.status === 404)) { _context.next = 34; break; } throw new NotFoundError(fetchResponse, errorData || 'not-found'); case 34: if (!(fetchResponse.status < 500)) { _context.next = 36; break; } throw new UserError(fetchResponse, errorData || 'user-error'); case 36: throw new ServerError(fetchResponse, errorData || 'server-error'); case 37: case "end": return _context.stop(); } }, _callee, this); })); function get(_x, _x2) { return _get.apply(this, arguments); } return get; }() }]); return ApiClient; }(); var ODS_DATASET_FIELD_TYPE = { TEXT: 'text', INT: 'int', DOUBLE: 'double', BOOLEAN: 'boolean', GEO_SHAPE: 'geo_shape', GEO_POINT_2D: 'geo_point_2d', DATETIME: 'datetime', DATE: 'date', FILE: 'file', JSON_BlOB: 'json_blob' // image and json aren't actually used for datasets anymore }; var ODS_DATASET_FIELD_SEMANTIC_TYPE = { IP_ADDRESS: 'ip_address', MONITORING_IP_ADDRESS: 'monitoring_ip_address' }; var ODS_METADATA_TEMPLATE_TYPE = { ADMIN: 'admin', BASIC: 'basic', INTEROP: 'interop', EXTRA: 'extra' }; var ODS_METADATA_TEMPLATE_FIELD_TYPE = { TEXT: 'text', ENUM: 'enum', ENUM_LIST: 'enumlist', URI_ENUM: 'uri_enum', URI_ENUM_LIST: 'uri_enumlist', LIST: 'list', DATE: 'date', DATE_TIME: 'datetime', BOOLEAN: 'boolean', INTEGER: 'int', DECIMAL: 'double', HTML: 'html', LONG_STRING: 'longstring', /** It stores a value that references a polygon, a linear ring, multiple polygons, multiple lines, or multiple points */ GEO_SHAPE: 'geo_shape', JSON: 'json', IMAGE: 'image' }; var EXPORT_DATASET_FORMAT = { JSON: 'json', GEOJSON: 'geojson', SHP: 'shp', CSV: 'csv', XLSX: 'xlsx', KML: 'kml', JSONLD: 'jsonld', JSONL: 'jsonl', RDFXML: 'rdfxml', TURTLE: 'turtle', N3: 'n3', MVT: 'mvt', PARQUET: 'parquet', FGB: 'fgb', GPX: 'gpx', ICAL: 'ical' }; var EXPORT_CATALOG_FORMAT = { CSV: 'csv', JSON: 'json', XLSX: 'xlsx', RDF: 'rdf', TTL: 'ttl', DATA_JSON: 'data.json', RSS: 'rss', DCAT: 'dcat', DCAT_AP_CH: 'dcat-ap-ch', DCAT_AP_IT: 'dcat-ap-it', DCAT_AP_DE: 'dcat-ap-de', DCAT_AP_SE: 'dcat-ap-se', DCAT_AP_SP: 'dcat-ap-sp', DCAT_AP_V1: 'dcat-ap-v1', DCAT_AP_BENAP: 'dcat_ap_benap' }; var Query = /*#__PURE__*/function () { function Query() { var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var init = arguments.length > 1 ? arguments[1] : undefined; _classCallCheck(this, Query); this.searchParams = undefined; this.params = init ? _objectSpread2({}, init) : {}; this.path = path; } _createClass(Query, [{ key: "getPath", value: function getPath() { return this.path; } }, { key: "getSearchParams", value: function getSearchParams() { var _this = this; if (this.searchParams === undefined) { this.searchParams = new URLSearchParams(); Object.entries(this.params).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), name = _ref2[0], value = _ref2[1]; if (_this.searchParams) { if (typeof value === 'string') { var _this$searchParams; (_this$searchParams = _this.searchParams) === null || _this$searchParams === void 0 || _this$searchParams.set(name, value); } else { _toConsumableArray(value).sort().forEach(function (itValue) { var _this$searchParams2; (_this$searchParams2 = _this.searchParams) === null || _this$searchParams2 === void 0 || _this$searchParams2.append(name, itValue); }); } } }); this.searchParams.sort(); } return this.searchParams; } }, { key: "toString", value: function toString() { var searchParams = this.getSearchParams().toString(); if (searchParams) searchParams = "?".concat(searchParams); return "".concat(this.getPath()).concat(searchParams); } }, { key: "set", value: function set(name, value) { var newParams = update(this.params, { $merge: _defineProperty({}, name, value) }); if (newParams === this.params) return this; return new Query(this.path, newParams); } }, { key: "unset", value: function unset(name) { var newParams = update(this.params, { $unset: [name] }); if (newParams === this.params) return this; return new Query(this.path, newParams); } }, { key: "update", value: function update(name, value) { if (!value) { return this; } var current = this.params[name]; var newValue = ''; if (typeof value === 'string') newValue = value;else if (typeof current === 'string') newValue = value(current || '');else newValue = value((current === null || current === void 0 ? void 0 : current[0]) || ''); return this.set(name, newValue); } }, { key: "append", value: function append(name, value) { var currentValue = this.params[name]; var newValue = null; if (currentValue === undefined) { newValue = [value]; } else if (typeof currentValue === 'string') { newValue = [currentValue, value]; } else { newValue = [].concat(_toConsumableArray(currentValue), [value]); } return this.set(name, newValue); } }, { key: "select", value: function select(expressions) { return this.update('select', expressions); } }, { key: "where", value: function where(filters) { return this.update('where', filters); } }, { key: "groupBy", value: function groupBy(expressions) { return this.update('group_by', expressions); } }, { key: "orderBy", value: function orderBy(expressions) { return this.update('order_by', expressions); } }, { key: "limit", value: function limit(_limit) { if (typeof _limit === 'number') return this.set('limit', _limit.toString()); return this.update('limit', _limit && function (current) { return _limit(Number(current)).toString(); }); } }, { key: "offset", value: function offset(_offset) { if (typeof _offset === 'number') return this.set('offset', _offset.toString()); return this.update('offset', _offset && function (current) { return _offset(Number(current)).toString(); }); } }, { key: "facet", value: function facet(_facet) { return this.append('facet', _facet); } }, { key: "refine", value: function refine(_refine) { return this.append('refine', _refine); } }, { key: "exclude", value: function exclude(_exclude) { return this.append('exclude', _exclude); } }, { key: "lang", value: function lang(_lang) { return this.set('lang', _lang); } }, { key: "timezone", value: function timezone(_timezone) { return this.set('timezone', _timezone); } }]); return Query; }(); function root(source) { return function () { return { itself: function itself() { return new Query("".concat(source, "/")); }, facets: function facets() { return new Query("".concat(source, "/facets/")); }, datasets: function datasets() { return new Query("".concat(source, "/datasets/")); }, /** * FIXME: Update this URL or remove this comment when the endpoint is out of beta. * The assets endpoint is still in development and not yet documented. * Therefore, this URL may change in the future. */ assets: function assets() { return new Query("".concat(source, "/assets/")); }, "export": function _export(format) { return new Query("".concat(source, "/exports/").concat(format, "/")); }, dataset: function dataset(datasetId) { return { itself: function itself() { return new Query("".concat(source, "/datasets/").concat(datasetId, "/")); }, facets: function facets() { return new Query("".concat(source, "/datasets/").concat(datasetId, "/facets/")); }, records: function records() { return new Query("".concat(source, "/datasets/").concat(datasetId, "/records/")); }, "export": function _export(format) { return new Query("".concat(source, "/datasets/").concat(datasetId, "/exports/").concat(format, "/")); }, record: function record(recordId) { return new Query("".concat(source, "/datasets/").concat(datasetId, "/records/").concat(recordId, "/")); } }; } }; }; } var fromCatalog = root('catalog'); var fromMonitoring = root('monitoring'); var fromDataNetwork = root('opendatasoft'); var field = function field(fieldName) { return "`".concat(fieldName.replace(/`/g, '\\`'), "`"); }; var string = function string(value) { return JSON.stringify(value); }; var dateTime = function dateTime(date) { return "date'".concat(date.toISOString(), "'"); }; /** * ODSQL function to normalize field name. * * - Can be used for `order_by` and `group_by` clauses. * - Example usage: `select=count(*) & group_by=lower(artist)`. * * @param {string} fieldName - The field name to normalize. * @returns {string} The lower ODSQL function. */ var lower = function lower(fieldName) { return "lower(".concat(fieldName, ")"); }; function inlineMonthOrDay(value) { if (value === undefined) return ''; if (value < 10) return "-0".concat(value); return "-".concat(value); } /** Format year month year and day numbers into an API call format. If you have an YYYY-MM-DD string already, use FromIsoString instead. */ var date = function date(_ref3) { var year = _ref3.year, month = _ref3.month, day = _ref3.day; return "date'".concat(year).concat(inlineMonthOrDay(month)).concat(inlineMonthOrDay(day), "'"); }; /** Formats an YYYY-MM-DD date string into an API call string. * Avoids converting to number if you already have a string. */ var dateFromIsoString = function dateFromIsoString(dateStr) { return "date'".concat(dateStr, "'"); }; var all = function all() { for (var _len = arguments.length, conditions = new Array(_len), _key = 0; _key < _len; _key++) { conditions[_key] = arguments[_key]; } return conditions.filter(Boolean).map(function (condition) { return "(".concat(condition, ")"); }).join(' AND '); }; var one = function one() { for (var _len2 = arguments.length, conditions = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { conditions[_key2] = arguments[_key2]; } return conditions.filter(Boolean).map(function (condition) { return "(".concat(condition, ")"); }).join(' OR '); }; var list = function list() { for (var _len3 = arguments.length, values = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { values[_key3] = arguments[_key3]; } return values.filter(Boolean).join(','); }; var not = function not(condition) { return condition ? "not (".concat(condition, ")") : ''; }; var formatFields = function formatFields(fields) { if (!fields || fields.length === 0) return ''; return "".concat(fields.map(field).join(', '), ", "); }; /** * Perform full-text search on fields, either ones specified in textFields, or all fields . It's a fuzzy search that finds matches even if the searched string is not an exact match. Equivalent to [ODSQL search predicade](https://help.opendatasoft.com/apis/ods-explore-v2/explore_v2.1.html#section/ODSQL-predicates/search()) * @param text Text to search for * @param textFields Fields to search in * @returns An ODSQL query, ready to be used as a `where` clause */ var textSearch = function textSearch(text) { var textFields = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; return "search(".concat(formatFields(textFields)).concat(string(text), ")"); }; /** * Perform full-text search on fields, either ones specified in textFields, or all fields. It matches the text fields that contain strings beginning with the searched string. Equivalent to [ODSQL startsWith predicade](https://help.opendatasoft.com/apis/ods-explore-v2/explore_v2.1.html#section/ODSQL-predicates/startswith()) * @param text Text to search for * @param textFields Fields to search in * @returns An ODSQL query, ready to be used as a `where` clause */ var textStartWith = function textStartWith(text) { var textFields = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; return "startswith(".concat(formatFields(textFields)).concat(string(text), ")"); }; /** * Perform full-text search on fields, either ones specified in textFields, or all fields. It matches the text fields that contain individual terms beginning the searched string. Equivalent to [ODSQL suggest predicade](https://help.opendatasoft.com/apis/ods-explore-v2/explore_v2.1.html#section/ODSQL-predicates/suggest()) * @param text Text to search for * @param textFields Fields to search in * @returns An ODSQL query, ready to be used as a `where` clause */ var textSuggest = function textSuggest(text) { var textFields = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; return "suggest(".concat(formatFields(textFields)).concat(string(text), ")"); }; /** * Perform an exact query on a given field. It matches when the field contains exactly the passed value. * @param fieldName Field name to query for * @param value Value to match on * @returns An ODSQL query, ready to be used as a `where` clause */ var exactMatch = function exactMatch(fieldName, value) { return "".concat(field(fieldName), "=").concat(string(value)); }; export { ApiClient, AuthenticationError, EXPORT_CATALOG_FORMAT, EXPORT_DATASET_FORMAT, NotFoundError, ODS_DATASET_FIELD_SEMANTIC_TYPE, ODS_DATASET_FIELD_TYPE, ODS_METADATA_TEMPLATE_FIELD_TYPE, ODS_METADATA_TEMPLATE_TYPE, Query, ServerError, UserError, all, date, dateFromIsoString, dateTime, exactMatch, field, fromCatalog, fromDataNetwork, fromMonitoring, list, lower, not, one, string, textSearch, textStartWith, textSuggest }; //# sourceMappingURL=index.es.js.map