squde-wp-api
Version:
Publish to npm:
499 lines (495 loc) • 21.6 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var cache = {};
var requests = [];
var Wordpress = /** @class */ (function () {
function Wordpress(endpoint) {
this.endpoint = endpoint;
}
Object.defineProperty(Wordpress.prototype, "posts", {
get: function () {
var api = this;
return {
get: function (params, signal, returnResponse, priority) {
if (params === void 0) { params = {}; }
if (signal === void 0) { signal = null; }
if (returnResponse === void 0) { returnResponse = false; }
if (priority === void 0) { priority = 10; }
return api.get('posts/?' + api.buildQuery(params), signal, '/wp/v2/', returnResponse, priority);
}
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Wordpress.prototype, "singlePost", {
get: function () {
var api = this;
return {
get: function (id, signal, priority) {
if (signal === void 0) { signal = null; }
if (priority === void 0) { priority = 10; }
return api.get('posts/' + id, signal, undefined, undefined, priority);
}
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Wordpress.prototype, "singlePostByQuery", {
get: function () {
var api = this;
return {
get: function (params, signal, priority) {
if (params === void 0) { params = {}; }
if (signal === void 0) { signal = null; }
if (priority === void 0) { priority = 10; }
return api.posts.get(params, signal, false, priority).then(function (posts) {
if (posts[0]) {
return posts[0];
}
return null;
});
}
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Wordpress.prototype, "products", {
get: function () {
var api = this;
return {
get: function (params, signal, returnResponse, priority) {
if (params === void 0) { params = {}; }
if (signal === void 0) { signal = null; }
if (returnResponse === void 0) { returnResponse = false; }
if (priority === void 0) { priority = 10; }
return api.get('products/?' + api.buildQuery(params), signal, '/squde/v1/', returnResponse, priority);
}
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Wordpress.prototype, "singleProduct", {
get: function () {
var api = this;
return {
get: function (id, signal, priority) {
if (signal === void 0) { signal = null; }
if (priority === void 0) { priority = 10; }
return api.get('products/' + id, signal, '/squde/v1/', undefined, priority);
}
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Wordpress.prototype, "singleProductByQuery", {
get: function () {
var api = this;
return {
get: function (params, signal, priority) {
if (params === void 0) { params = {}; }
if (signal === void 0) { signal = null; }
if (priority === void 0) { priority = 10; }
return api.products.get(params, signal, false, priority).then(function (products) {
if (products[0]) {
return products[0];
}
return null;
});
}
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Wordpress.prototype, "pages", {
get: function () {
var api = this;
return {
get: function (params, signal, priority) {
if (params === void 0) { params = {}; }
if (signal === void 0) { signal = null; }
if (priority === void 0) { priority = 10; }
return api.get('pages/?' + api.buildQuery(params), signal, undefined, undefined, priority);
}
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Wordpress.prototype, "page", {
get: function () {
var api = this;
return {
get: function (params, signal, priority) {
if (params === void 0) { params = {}; }
if (signal === void 0) { signal = null; }
if (priority === void 0) { priority = 10; }
return api.pages.get(params, signal, priority).then(function (pages) {
if (pages[0]) {
return pages[0];
}
return null;
});
}
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Wordpress.prototype, "frontpage", {
get: function () {
var api = this;
return {
get: function (signal, priority) {
if (signal === void 0) { signal = null; }
if (priority === void 0) { priority = 10; }
return api.get('frontpage', signal, undefined, undefined, priority);
}
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Wordpress.prototype, "menus", {
get: function () {
var api = this;
return {
get: function (params, signal, priority) {
if (params === void 0) { params = {}; }
if (signal === void 0) { signal = null; }
if (priority === void 0) { priority = 10; }
return api.get('menus/?' + api.buildQuery(params), signal, undefined, undefined, priority);
}
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Wordpress.prototype, "submissions", {
get: function () {
var api = this;
return {
post: function (params, signal, priority) {
if (params === void 0) { params = {}; }
if (signal === void 0) { signal = null; }
if (priority === void 0) { priority = 10; }
var select = document.querySelectorAll('script[src^="https://www.google.com/recaptcha/api.js"]');
var postSubmissions = function (data) {
if (data === void 0) { data = {}; }
return api.post('submissions/', data, signal, undefined, undefined, priority);
};
if (select.length === 0) {
return postSubmissions(params);
}
else {
var siteKey = select[0].src.split('?render=')[1];
// @ts-ignore
return window.grecaptcha.execute(siteKey, { action: 'submit' }).then(function (token) {
var isFormData = function (v) {
return v && typeof v.append === 'function' && typeof v.get === 'function' && typeof v.has === 'function';
};
if (isFormData(params)) {
params.append('g-recaptcha-response', token);
return postSubmissions(params);
}
params['g-recaptcha-response'] = token;
return postSubmissions(params);
});
}
}
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Wordpress.prototype, "media", {
get: function () {
var api = this;
return {
get: function (params, signal, priority) {
if (params === void 0) { params = {}; }
if (signal === void 0) { signal = null; }
if (priority === void 0) { priority = 10; }
return api.get('media/?' + api.buildQuery(params), signal, undefined, undefined, priority);
}
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Wordpress.prototype, "image", {
get: function () {
var api = this;
return {
get: function (id, signal, priority) {
if (signal === void 0) { signal = null; }
if (priority === void 0) { priority = 10; }
return api.get('media/' + id, signal, undefined, undefined, priority).then(function (image) {
return image;
});
}
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Wordpress.prototype, "auth", {
get: function () {
var api = this;
return {
login: function (credentials, signal) {
if (signal === void 0) { signal = null; }
return api.post('token/', credentials, signal, '/jwt-auth/v1/')
.then(function (result) {
if ('token' in result) {
var token = result.token;
window.localStorage.setItem('x-user-token', token);
window.localStorage.setItem('x-user-details', JSON.stringify(result));
return result;
}
throw result;
});
},
logout: function () {
window.localStorage.removeItem('x-user-token');
window.localStorage.removeItem('x-user-details');
return Promise.resolve();
},
validate: function (signal) {
if (signal === void 0) { signal = null; }
if (!window.localStorage.getItem('x-user-token') || !window.localStorage.getItem('x-user-details')) {
return Promise.reject(new Error('No token present'));
}
return api.post('token/validate', {}, signal, '/jwt-auth/v1/')
.then(function (data) {
var details = window.localStorage.getItem('x-user-details');
if (details !== null) {
data.details = JSON.parse(details);
}
return data;
});
}
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Wordpress.prototype, "user", {
get: function () {
var api = this;
return {
update: function (params, signal) {
if (params === void 0) { params = {}; }
if (signal === void 0) { signal = null; }
var userDataStr = window.localStorage.getItem('x-user-details');
if (userDataStr) {
var userData_1 = JSON.parse(userDataStr);
return api.post('users/' + userData_1.ID, params, signal)
.then(function (user) {
userData_1.user_email = user.email;
userData_1.user_display_name = user.name;
window.localStorage.setItem('x-user-details', JSON.stringify(userData_1));
return user;
});
}
throw new Error('No userdata present');
}
};
},
enumerable: true,
configurable: true
});
Wordpress.prototype.get = function (path, signal, prefix, returnResponse, priority) {
if (signal === void 0) { signal = null; }
return this.request(path, 'GET', {}, signal, prefix, returnResponse, priority);
};
Wordpress.prototype.post = function (path, data, signal, prefix, returnResponse, priority) {
if (signal === void 0) { signal = null; }
return this.request(path, 'POST', data, signal, prefix, returnResponse, priority);
};
Wordpress.prototype.buildQuery = function (data) {
// return a multidimensional object as a query string
if (typeof data === 'object') {
return Object.keys(data).map(function (key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
}).join('&');
}
return data;
};
Wordpress.prototype.fixData = function (data) {
var _this = this;
var isArray = !!data && !!data[0];
if (!isArray) {
data = [data];
}
if (!data.map) {
return data;
}
data = data.map(function (row) {
if (row === null || typeof row !== 'object') {
return row;
}
if (row.content && row.content.rendered) {
row.content = row.content.rendered;
}
if (row.excerpt && row.excerpt.rendered) {
row.excerpt = row.excerpt.rendered;
}
if (row.guid && row.guid.rendered) {
row.guid = row.guid.rendered;
}
if (row.title && row.title.rendered) {
row.title = row.title.rendered;
}
if (row.date) {
row.date = new Date(row.date);
}
if (row.date_gmt) {
row.date_gmt = new Date(row.date_gmt);
}
if (row.modified) {
row.modified = new Date(row.modified);
}
if (row.modified_gmt) {
row.modified_gmt = new Date(row.modified_gmt);
}
if (row.permalink && !row.link) {
row.link = row.permalink;
}
if (!row.url && row.link) {
row.url = row.link;
}
if (row.url && row.url.split('://').length > 1 && (row.url.split(window.location.host).length > 1 || row.url.split('.local').length > 1)) {
row.url = row.url.split('://')[1];
row.url = row.url.split('/');
delete row.url[0];
row.url = row.url.join('/', row.url);
}
if (row.subMenu) {
row.subMenu = _this.fixData(row.subMenu);
}
return row;
});
if (!isArray) {
return data[0];
}
return data;
};
Wordpress.prototype.request = function (path, method, postData, signal, prefix, returnResponse, priority) {
var _this = this;
if (postData === void 0) { postData = {}; }
if (signal === void 0) { signal = null; }
if (priority === void 0) { priority = 10; }
var thisObject = this;
if (cache[path] && method === 'GET') {
if (typeof cache[path].then === 'function') {
return cache[path];
}
if (!returnResponse) {
return Promise.resolve(cache[path]);
}
}
cache[path] = new Promise(function (resolve) {
requests.push({ path: path, priority: priority });
setTimeout(function () {
var firstHigherPriorityRequest = requests
.filter(function (request) { return request.path !== path; })
.filter(function (request) { return request.priority < priority; })
.sort(function (requestA, requestB) {
return requestA.priority > requestB.priority ? -1 : 1;
})
.map(function (request) { return cache[request.path]; })
.filter(function (cachePath) { return cachePath && typeof cachePath.then === 'function'; })[0];
// Priority logging
// // tslint:disable-next-line:no-console
// console.log('begin: ' + path);
// // tslint:disable-next-line:no-console
// console.log(requests
// .filter((request: IRequestParameters) => request.path !== path)
// .filter((request: IRequestParameters) => request.priority < priority)
// .sort((requestA: IRequestParameters, requestB: IRequestParameters) => {
// return requestA.priority > requestB.priority ? -1 : 1;
// })
// .filter((request: IRequestParameters) => cache[request.path] && typeof cache[request.path].then === 'function')
// .map((request: IRequestParameters) => request.path));
// // tslint:disable-next-line:no-console
// console.log('end: ' + path);
var thisRequest = (function () {
var args = {
method: method
};
if (signal) {
args.signal = signal;
}
args.headers = {};
if (method === 'POST') {
var isFormData = function (v) {
return v && typeof v.append === 'function' && typeof v.get === 'function' && typeof v.has === 'function';
};
if (isFormData(postData)) {
args.body = postData;
}
else {
args.body = _this.buildQuery(postData);
args.headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
}
}
var token = window.localStorage.getItem('x-user-token');
if (!!token && token.length > 0) {
args.headers.Authorization = 'Bearer ' + token;
}
var endpoint = _this.endpoint;
if (prefix) {
endpoint = endpoint.split('/wp/v2/').join(prefix);
}
cache[path] = fetch(endpoint + path, args)
.then(function (response) {
requests = requests.filter(function (request) { return request.path !== path; });
if (response.status === 200) {
if (returnResponse) {
cache[path] = undefined;
return response;
}
return response.json().then(function (data) {
cache[path] = thisObject.fixData(data);
return cache[path];
});
}
else {
throw response;
}
})
.catch(function (error) {
requests = requests.filter(function (request) { return request.path !== path; });
if (error.status === 403 && token !== null) {
return _this.auth.logout().then(function () {
window.location.reload();
});
}
throw error;
});
return cache[path];
});
if (firstHigherPriorityRequest) {
firstHigherPriorityRequest.then(function () {
resolve(thisRequest());
});
}
else {
resolve(thisRequest());
}
});
});
return cache[path];
};
return Wordpress;
}());
exports.default = Wordpress;
//# sourceMappingURL=index.js.map