UNPKG

ngx-drupal7-services

Version:

# Angular 2+/Ionic 2+ Drupal 7 Services #### Typescript angular module for [Drupal Services 3.x](https://www.drupal.org/project/services)

1,280 lines (1,261 loc) 47.9 kB
import { of, throwError } from 'rxjs'; import * as i0 from '@angular/core'; import { PLATFORM_ID, Injectable, Inject, APP_INITIALIZER, NgModule } from '@angular/core'; import * as i1 from '@angular/common/http'; import { HttpClientModule } from '@angular/common/http'; import { map, timeout, catchError, mergeMap } from 'rxjs/operators'; import { isPlatformServer } from '@angular/common'; /** * DrupalConstants singleton design pattern of the required settings and user connection. */ // @dynamic class DrupalConstants { constructor() { /** * handle offline error messages * @param err (optional) the error of the http request */ this.handleOffline = function (err) { if (this.settings.allowOffline) { return of(); } return throwError(err); }; } static get Instance() { if (!this.instance) { this.instance = new DrupalConstants(); } return this.instance; } /** * Handeling the case when user didn't implement the back-end settings and return the settings instance */ static get Settings() { if (!this.Instance.settings) { throw new Error('ngx-drupal7-services: Application settings are not set, Please read README.MD file'); } return this.Instance.settings; } /** * Set the settings instanse on application init. * you can also do that at the runtime, Thanks to Singleton design pattern <3 ! */ static set Settings(newSettings) { this.Instance.settings = newSettings; } /** * the full backend url for current user settings */ static get backEndUrl() { const settings = this.Settings; const url = settings.apiProtocol + '://' + settings.apiHost; return settings.apiPort ? url + ':' + settings.apiPort + '/' : url + '/'; } /** * Application back-end rest api url. */ static get restUrl() { const settings = this.Settings; return this.backEndUrl + settings.apiEndPoint + '/'; } /** * Updating connection instanse after login or rightaway after openning the connection */ static set Connection(newConnection) { this.Instance.connection = newConnection; } /** * get the connection instance */ static get Connection() { return this.Instance.connection; } } /** * the main service is the basic http service of all other services "parent" that implements all the required request. * this service will add the headers automatically for each request it self */ class MainService { /** * the main constractor of this service will inject the required services dynamically. * @param http basic http service * @param cookieService ngx-cookie service provider to save the cookies * @see https://angular.io/guide/dependency-injection * @see https://www.npmjs.com/package/ngx-cookie */ constructor(httpClient, platformId) { this.httpClient = httpClient; this.platformId = platformId; } /** * structure a full entity for drupal request * @param entity the entity to be structured * @param ignoredFields fields to be ignored just like nid or uid or title * @param fieldLabels: the label for each field just like "{field_custom_field: 'value'}" * @param language language of the entity */ structureEntity(entity, ignoredFields, fieldLabels, language) { Object.keys(entity).forEach((key, index) => { if (ignoredFields.indexOf(key) === -1) { let fieldLabel; if (fieldLabels[key]) { fieldLabel = fieldLabels[key]; } entity[key] = this.structureField(entity[key], fieldLabel, language); } }); return entity; } /** * structure the field for drupal services request * @param value the field value * @param label field label name * @param language language of the field */ structureField(value, label = 'value', language) { if (!language) { language = DrupalConstants.Settings.language; } const item = {}; if (this.isArray(value)) { const field_array = []; for (let i = 0, l = value.length; i < l; i++) { item[label] = value[i]; field_array.push(item); } return { [language]: field_array }; } if (value instanceof Date) { const obj = { value: { date: `${value.getFullYear()}-${value.getMonth() + 1}-` + `${value.getDate()} ${value.getHours()}:${value.getMinutes()}:${value.getSeconds()}` } }; return { [language]: [ obj ] }; } // field value given with label(s) already built if (typeof value === 'object') { return { [language]: [ value ] }; } item[label] = value; return { [language]: [ item ] }; } /** * a getter to return the required headers for drupal * X-CSRF-Token - application token from services/session/connect * Content-Type - the type of the request content. * Accept - forcing drupal to return the response as a json object * @return object of the headers */ get options() { const headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', }; const token = this.getSavedVariable('token'); if (token) { headers['X-CSRF-Token'] = token; } headers['Authentication'] = `${this.getSavedVariable('session_name')}=${this.getSavedVariable('sessid')}`; if (DrupalConstants.Settings.cookieHeader) { headers['Cookie'] = `${this.getSavedVariable('session_name')}=${this.getSavedVariable('sessid')}`; } const options = { headers: headers, withCredentials: true, reportProgress: true, }; return options; } /** * getting token from drupal services module * @return http text token response */ getToken() { const options = this.options; options['responseType'] = 'text'; return this.httpRequestWithConfig(this.httpClient.get(`${DrupalConstants.backEndUrl}services/session/token`, options)).pipe(map(res => { if (!isPlatformServer(this.platformId)) { localStorage.setItem('token', res); } return res; })); } /** * Saving drupal session and token in cookies using ngx-cookie service * @param connection drupal connection */ saveSessionToken(connection) { if (!connection.token) { connection.token = this.getSavedVariable('token'); } this.removeSession(); DrupalConstants.Connection = connection; if (!isPlatformServer(this.platformId)) { localStorage.setItem(connection.session_name, connection.sessid); localStorage.setItem('sessid', connection.sessid); localStorage.setItem('session_name', connection.session_name); localStorage.setItem('token', connection.token); if (connection.user && connection.user.timestamp) { localStorage.setItem('timestamp', connection.user.timestamp.toString()); } else { localStorage.setItem('timestamp', Math.floor(Date.now()).toString()); } } } /** * building up the full url path for each resource and / or params * @param resource the entity resource param. ex: system/'connect', user/'login' * @return full request path after adding the entity type and resource param */ fullRequestURL(resource) { let request_url = DrupalConstants.restUrl; if (this.entityType) { request_url += this.entityType; } if (resource) { if (request_url[request_url.length - 1] === '/') { request_url += resource; } else { request_url += '/' + resource; } } return request_url; } /** * adding http request configs: request timeout, error handler * @param httpObservableRequest the http Observable to request * @return Observable of the request after adding required configs */ httpRequestWithConfig(httpObservableRequest) { return httpObservableRequest.pipe(timeout(DrupalConstants.Settings.requestTimeout), catchError(err => DrupalConstants.Instance.handleOffline(err))); } /** * basic http get request with headers. * @param resource the entity resource param. ex: system/'connect', user/'login' * @return http json response */ get(resource) { return this.httpRequestWithConfig(this.httpClient.get(this.fullRequestURL(resource), this.options)); } /** * basic http post request with headers. * @param resource the entity resource param. ex: system/'connect', user/'login' * @param body the contenct of the request * @return http json response */ post(body = {}, resource) { return this.httpRequestWithConfig(this.httpClient.post(this.fullRequestURL(resource), body, this.options)); } /** * basic http put request with headers. * @param resource the entity resource param. ex: system/'connect', user/'login' * @param body the contenct of the request * @return http json response */ put(body = {}, resource) { return this.httpRequestWithConfig(this.httpClient.put(this.fullRequestURL(resource), body, this.options)); } /** * basic http delete request with headers. * @param resource the entity resource param. ex: system/'connect', user/'login' * @return http json response */ delete(resource) { return this.httpRequestWithConfig(this.httpClient.delete(this.fullRequestURL(resource), this.options)); } /** * Clearing drupal session after logging out */ removeSession() { if (!isPlatformServer(this.platformId)) { localStorage.removeItem('token'); localStorage.removeItem('timestamp'); localStorage.removeItem('sessid'); localStorage.removeItem('session_name'); if (DrupalConstants.Connection && DrupalConstants.Connection.session_name) { localStorage.removeItem(DrupalConstants.Connection.session_name); } } } /** * Checking the current connection if the connection is init and valid * @return if connection is valid */ isConnected() { return this.getSavedVariable('token') && this.getSavedVariable('sessid') && this.getSavedVariable('session_name') && !this.isConnectionExpired() ? true : false; } /** * Check if the drupal session is timedout. * @return true if the current date is less than the login date by 24 day "drupal default session timeout is 24 day". */ isConnectionExpired() { const nowTS = Math.floor(Date.now()); let sessionDays = 23; if (DrupalConstants.Settings.sessionDays) { sessionDays = DrupalConstants.Settings.sessionDays; } const dayMS = 86400000; // 1 day to ms const expirationTS = sessionDays * dayMS; return nowTS - +this.getSavedVariable('timestamp') < expirationTS; } /** * Serializin arguments as a string * @param options object of drupal parametars to serialize * @return string of parameters */ getArgs(options) { if (!options) { return ''; } let args = '?'; Object.keys(options).forEach((key, index) => { args += this.optionToString(key, options[key]); }); return args; } /** * Check if variable is array of objects * @param value array to check */ isArray(value) { return Object.prototype.toString.call(value) === '[object Array]'; } /** * retrive the variable from the connection object or if there is no connection yet it will return them from the cookies * this will will allow you to implement your custom connection storage, just like ionic. * because the cookies is not always available on webview apps, you may need to save the connection in sqllite * and restore them directly. * @param variableName the name of the saved variable */ getSavedVariable(variableName) { if (DrupalConstants.Connection) { if (DrupalConstants.Connection[variableName]) { return DrupalConstants.Connection[variableName]; } else if (DrupalConstants.Connection.user && DrupalConstants.Connection.user[variableName]) { return DrupalConstants.Connection.user[variableName]; } } if (!isPlatformServer(this.platformId)) { return localStorage.getItem(variableName); } return; } /** * serializing eatch option * @param key option key * @param value option value * @return single option serilization */ optionToString(key, value) { if (!value) { return ''; } let str = ''; if (value instanceof Array) { value.forEach((element, index) => { str += `${key}[${index}]=${element}&`; }); } else if (value instanceof Object) { Object.keys(value).forEach((element, index) => { if (value[element] instanceof Object) { str += this.serializeObject(value[element], `${key}[${element}]`); } else { str += `${key}[${element}]=${value[element]}&`; } }); } else { str += `${key}=${value}&`; } return str; } /** * serializing the object keys * @param obj object to serialize */ serializeObject(obj, parentSerialized) { let str = ''; Object.keys(obj).forEach((key, index) => { const value = obj[key]; if (value instanceof Object) { str += `${this.serializeObject(value, `${parentSerialized}[${key}]`)}`; } else { str += `${parentSerialized}[${key}]=${value}&`; } }); return str; } } /** @nocollapse */ MainService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: MainService, deps: [{ token: i1.HttpClient }, { token: PLATFORM_ID }], target: i0.ɵɵFactoryTarget.Injectable }); /** @nocollapse */ MainService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: MainService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: MainService, decorators: [{ type: Injectable }], ctorParameters: function () { return [{ type: i1.HttpClient }, { type: Object, decorators: [{ type: Inject, args: [PLATFORM_ID] }] }]; } }); /** * system service for drupal * @see BACK_END/admin/structure/services/list/END_POINT/resources for more details */ class SystemService extends MainService { constructor() { super(...arguments); this.entityType = 'system'; } /** * if there is already a token in the browser cookies and it is not expired it will return it * this will fetch a new token before trying to connect * @param refreshToken boolean to force the application to request new token * @return observable of the connect method * the subscription data is an object of SystemConnection interface */ connect(refreshToken = false) { if (this.isConnectionExpired()) { this.removeSession(); } if (!DrupalConstants.Connection || !DrupalConstants.Connection.token || refreshToken) { return this.getToken().pipe(mergeMap(token => { return this.post({}, 'connect').pipe(map(connection => { connection.token = token; this.saveSessionToken(connection); return connection; })); })); } return this.post({}, 'connect').pipe(map(connection => { this.saveSessionToken(connection); return connection; })); } /** * implement get_variable resource * @param variableName the name of the variable * @return the value of the variable */ getVariable(variableName) { return this.post({ name: variableName }, 'get_variable'); } /** * implement set_variable resource * @param variableName the name of the variable * @param value the value to set for the variable * @return always null, take care of overriding old variables with same name */ setVariable(variableName, value) { const variable = { name: variableName, value: value }; return this.post(variable, 'set_variable'); } /** * implement del_variable resource * @param variableName variable name to delete * @return null if variable found or not. */ delVariable(variableName) { return this.post({ name: variableName }, 'del_variable'); } } /** @nocollapse */ SystemService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: SystemService, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); /** @nocollapse */ SystemService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: SystemService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: SystemService, decorators: [{ type: Injectable }] }); /** * user service for drupal * @see BACK_END/admin/structure/services/list/END_POINT/resources for more details */ class UserService extends MainService { constructor() { super(...arguments); this.entityType = 'user'; } /** * implement retrive resource * @param uid user id to retrive * @return user object */ getUserById(uid) { return this.get(uid); } /** * implement index resource * @return array of users * Please notice that the user must have the required permission to do this action */ getUsersList() { return this.get(); } /** * implement create resource * @param user user to create * @return created user details */ createUser(user) { return this.post(user); } /** * implement update resource * @param user user object to update * @return updated user object */ updateUser(user) { return this.put(user, user.uid); } /** * implement delete * @param uid user id to delete * @return array of boolean, if user deleted will be true, otherwise will be false */ deleteUser(uid) { return this.delete(uid); } /** * implement login resource * @param user credentials to login "username and password" * @return system connection that contains the session details and the user object * notice that the user login version must be of version 1.0 at the resources settions at the back-end */ login(user) { const observer = this.post(user, 'login'); return observer.pipe(map((connection) => { this.saveSessionToken(connection); return connection; })); } /** * implement logout resource * @return new token after logging out */ logout() { const observer = this.post({}, 'logout'); return observer.pipe(mergeMap((loggedOut) => { if (loggedOut[0]) { this.removeSession(); return this.getToken(); } })); } /** * implement request_new_password resource * @param useranme the username of the user to request a new password * @return array of boolean, if the mail sent successfully will be true, otherwhise will be false. * if the server is not a mail server or if there is not mail server configuration this will always return false */ requestNewPassword(useranme) { const user = { name: useranme }; return this.post(user, 'request_new_password'); } /** * implement user_pass_reset resource * @param passwordReset Object of the sent details to the email that contains the timestamp and the hashed password * @return response of the password reset request * this request will automatically logging the user in for only one time and will be expired after the first use. * the hashed password can be found at the drupal reset password email and you can customize it if you have token module installed */ userPasswordReset(passwordReset) { return this.post(passwordReset, 'user_pass_reset'); } /** * implement register resource * @param user object to register new account * some properties is required if it is set at the account settings inside the drupal admin config * @see http://BACKEND/admin/config/people/accounts * @return created user details */ registerAccount(user) { return this.post(user, 'register'); } /** * implement cancel resource * @param uid the user id to cancel * @return array of boolean, true if canceled, false otherwhise * Please notice the cancelation settings is managed at the backend * @see http://BACKEND/admin/config/people/accounts */ cancelUser(uid) { return this.post({}, `${uid}/cancel`); } /** * implement password_reset resource * @param uid user id to reset his password * @return array of boolean, true if user password has been resetted, false otherwhise */ passwordReset(uid) { return this.post({}, `${uid}/password_reset`); } /** * implement resend_welcome_email * @param uid user id to send the email for his account * @return array of boolean, if the mail sent successfully will be true, otherwhise will be false. * if the server is not a mail server or if there is not mail server configuration this will always return false */ resendWelcomeEmail(uid) { return this.post({}, `${uid}/resend_welcome_email`); } /** * implement token */ token() { return this.getToken(); } } /** @nocollapse */ UserService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: UserService, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); /** @nocollapse */ UserService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: UserService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: UserService, decorators: [{ type: Injectable }] }); /** * node service for drupal * @see BACK_END/admin/structure/services/list/END_POINT/resources for more details */ class NodeService extends MainService { constructor() { super(...arguments); this.entityType = 'node'; } /** * impelement index resource * @return array of nodes */ getAllNodes() { return this.get(); } /** * implement retrive resource * @param nid node id to retrive * @return object of the node entity */ getNodeById(nid) { return this.get(nid); } /** * implement create resource * @param node node entity to create * @return created node details */ createNode(node) { return this.post(node); } /** * implement create resource * @param node node to create * @return created node details */ updateNode(node) { return this.put(node, node.nid); } /** * implement delete resource * @param nid node id to delete * @return array true if node deleted, otherwise return false array */ deleteNode(nid) { return this.delete(nid); } /** * implement files resource * @param nid node id * @return array of files that attached to that node */ files(nid) { return this.get(`${nid}/files`); } /** * implement comments resource * @param nid node id * @return array of comments that attached to that node */ comments(nid) { return this.get(`${nid}/comments`); } /** * implement attach_files resource * @param nid node id * @file object contains the field details and the file to upload * @return attached file */ attachFilesToNode(nid, file) { return this.post(file, `${nid}/attach_file`); } } /** @nocollapse */ NodeService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: NodeService, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); /** @nocollapse */ NodeService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: NodeService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: NodeService, decorators: [{ type: Injectable }] }); /** * file service for drupal * @see BACK_END/admin/structure/services/list/END_POINT/resources for more details */ class FileService extends MainService { constructor() { super(...arguments); this.entityType = 'file'; } /** * impelement index resource * @return array of files */ getAllFiles() { return this.get(); } /** * implement retrive resource * @param fid file id to retrive * @return object of the file entity */ getFileById(fid) { return this.get(fid); } /** * implement create resource * @param file file entity to create * @return created file details */ createFile(file) { return this.post(file); } /** * implement delete resource * @param fid file id to delete * @return boolean array if file deleted, otherwise return false * keep in mined that you can not delete a file if it is already referenced by a node */ deleteFile(fid) { return this.delete(fid); } /** * creating raw file * this require rest support for form multi data */ createRaw() { return this.post({}, 'create_raw'); } } /** @nocollapse */ FileService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: FileService, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); /** @nocollapse */ FileService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: FileService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: FileService, decorators: [{ type: Injectable }] }); /** * comment service for drupal * @see BACK_END/admin/structure/services/list/END_POINT/resources for more details */ class CommentService extends MainService { constructor() { super(...arguments); /** * entity type is comment */ this.entityType = 'comment'; } /** * implement comment index resource * @return list of comments */ getAllComments() { return this.get(); } /** * implement comment retrive method * @param cid comment id * @return drupal comment entity */ getCommentById(cid) { return this.get(cid); } /** * implement create resource * @param comment the comment to create * @return created comment details */ createComment(comment) { return this.post(comment); } /** * implement update resource * @param comment comment to update * @return array of comment id */ updateComment(comment) { return this.put(comment, comment.cid); } /** * implement delete resource * @param cid comment id to delete * @return array of boolean, if comment deleted the array will will contains true */ deleteComment(cid) { return this.delete(cid); } /** * implement countAll resource * @param nid host node id of the comments * @return number of comments on the node */ countAllCommentsByNodeId(nid) { return this.post({ nid: nid }, 'countAll'); } /** * implement countNew resource. * @param nid host node id of the new comments * @return number of the new comments for the giving node id */ countNewCommentsByNodeId(nid) { return this.post({ nid: nid }, 'countNew'); } } /** @nocollapse */ CommentService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: CommentService, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); /** @nocollapse */ CommentService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: CommentService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: CommentService, decorators: [{ type: Injectable }] }); /** * taxonomy term service for drupal * @see BACK_END/admin/structure/services/list/END_POINT/resources for more details */ class TaxonomyTermService extends MainService { constructor() { super(...arguments); this.entityType = 'taxonomy_term'; } /** * implement index resource * @return array of terms */ getAllTaxonomyTerms() { return this.get(); } /** * implement retrive resource * @param tid term id * @return term object */ getTaxonomyTermById(tid) { return this.get(tid); } /** * implement create resource * @param taxonomyTerm the term to create * @return array number for the wight of the term */ createTaxonomyTerm(taxonomyTerm) { return this.post(taxonomyTerm); } /** * implement update resource * @param taxonomyTerm term to update * @return array number for the wight of the term */ updateTaxonomyTerm(taxonomyTerm) { return this.put(taxonomyTerm, taxonomyTerm.tid); } /** * implement delete resource * @param tid term id to delete * @return array of deleted term id */ deleteTaxonomyTerm(tid) { return this.delete(tid); } /** * implement selectNodes * @param tid term id * @return array of nodes that referenced this term in one of the fields */ getAllNodesForTerm(tid) { return this.post({ tid: tid }, 'selectNodes'); } } /** @nocollapse */ TaxonomyTermService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: TaxonomyTermService, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); /** @nocollapse */ TaxonomyTermService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: TaxonomyTermService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: TaxonomyTermService, decorators: [{ type: Injectable }] }); /** * taxonomy vocabulary service for drupal * @see BACK_END/admin/structure/services/list/END_POINT/resources for more details */ class TaxonomyVocabularyService extends MainService { constructor() { super(...arguments); this.entityType = 'taxonomy_vocabulary'; } /** * implement index resource * @return array of the available vocabularies */ getAllVocabularies() { return this.get(); } /** * implement retrive resource * @param vid vocabulary id * @return vocabulary object */ getTaxonomyVocabularyById(vid) { return this.get(vid); } /** * implement create resource * @param taxonomyVocabulary the vocabulary to create * @return array of vocabulary id */ createTaxonomyVocabulary(taxonomyVocabulary) { return this.post(taxonomyVocabulary); } /** * implement update resource * @param taxonomyVocabulary the vocabulary to update * @return array of the current vocabulary whight */ updateTaxonomyVocabulary(taxonomyVocabulary) { return this.put(taxonomyVocabulary, taxonomyVocabulary.vid); } /** * implement delete resource * @param vid vocabulary id to delete * @return array of deleted vocabulary id */ deleteTaxonomyVocabulary(vid) { return this.delete(vid); } /** * implement retrieveByMachineName resource * @param vocabularyMachineName vocabulary machine name * @return vocabulary object */ getTaxonomyVocabularyByMachineName(vocabularyMachineName) { return this.post({ machine_name: vocabularyMachineName }, 'retrieveByMachineName'); } /** * implement getTree resource * @param vid vocabulary id * @return a full list of taxonomy terms inside this vocabulary as a tree structure. */ getTaxonomyVocabularyTree(vid) { return this.post({ vid: vid }, 'getTree'); } } /** @nocollapse */ TaxonomyVocabularyService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: TaxonomyVocabularyService, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); /** @nocollapse */ TaxonomyVocabularyService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: TaxonomyVocabularyService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: TaxonomyVocabularyService, decorators: [{ type: Injectable }] }); /** * view service for drupal using services_views module * @see https://www.drupal.org/project/services_views */ class ViewService extends MainService { constructor() { super(...arguments); this.entityType = 'views'; } /** * impelemnt retrive resource * @param viewMachineName view machine name * @param options parameters of filteration for this view * @return array of view rows OR view html code if the options format_output is 1 */ getView(viewMachineName, options) { const args = this.getArgs(options); return this.get(viewMachineName + args); } } /** @nocollapse */ ViewService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: ViewService, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); /** @nocollapse */ ViewService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: ViewService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: ViewService, decorators: [{ type: Injectable }] }); /** * custom entity service for drupal using services_entity module * @see https://www.drupal.org/project/services_entity */ class EntityService extends MainService { constructor() { super(...arguments); /** * the entity prefix for all the entities */ this.entityType = 'entity_'; } /** * getting the full entity url for the entity * @param entityMachineName entity machine name, ex: node, user * @return string of full path to resource */ fullRequestURL(entityMachineName) { let request_url = DrupalConstants.restUrl; request_url += this.entityType + entityMachineName; return request_url; } /** * implement index resource * @param entityMachineName entity machine name, ex: node, user * @param options parameter options * @return array of the required entity type. * personally suggest to create an interface for each type you want to retrive, * you can use the models in this module as a perent interfaces. */ indexEntity(entityMachineName, options) { const args = this.getArgs(options); return this.get(entityMachineName + args); } /** * implement retrive resource * @param entityMachineName entity machine name, ex: node, user * @param selector the id of the entity * @param options parameter options * @return entity object */ retrieveEntity(entityMachineName, selector, options) { const args = this.getArgs(options); return this.get(`${entityMachineName}/${selector}${args}`); } /** * implement delete resource * @param entityMachineName entity machine name, ex: node, user * @param selector the id of the entity * @return null if the entity is deleted,otherwise throws an error. */ deleteEntity(entityMachineName, selector) { return this.delete(`${entityMachineName}/${selector}`); } /** * implement create resource * @param entityMachineName entity machine name, ex: node, user * @param entity entity object to create * @return created entity */ createEntity(entityMachineName, entity) { return this.post(entity, entityMachineName); } /** * implement update resource * @param entityMachineName entity machine name, ex: node, user * @param entity entity to update * @param selector entity id to update and must match the id inside the entity object * @return updated entity */ updateEntity(entityMachineName, entity, selector) { return this.put(entity, `${entityMachineName}/${selector}`); } } /** @nocollapse */ EntityService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: EntityService, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); /** @nocollapse */ EntityService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: EntityService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: EntityService, decorators: [{ type: Injectable }] }); /** * menu service for drupal * @see https://www.drupal.org/project/services_menu for more details */ class MenuService extends MainService { constructor() { super(...arguments); this.entityType = 'menu'; } /** * implement menu retrive * @param menuMachineName menu machine name * @return menu witl all children links */ getMenu(menuMachineName) { return this.get(menuMachineName); } } /** @nocollapse */ MenuService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: MenuService, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); /** @nocollapse */ MenuService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: MenuService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: MenuService, decorators: [{ type: Injectable }] }); /** * facebook oauth service * @see https://www.drupal.org/project/services_fboauth * @see BACK_END/admin/structure/services/list/END_POINT/resources for more details */ class FacebookOAuthService extends MainService { constructor() { super(...arguments); this.entityType = 'fboauth'; } /** * if there is already a token in the browser cookies and it is not expired it returns * this will fetch a new token before trying to connect * @param accessToken string of the recieved access token * @return observable of the connect method * the subscription data is an object of SystemConnection interface */ connect(accessToken) { if (this.isConnectionExpired()) { this.removeSession(); } const body = { access_token: accessToken }; if (!DrupalConstants.Connection || !DrupalConstants.Connection.token) { return this.getToken().pipe(mergeMap(token => { return this.post(body, 'connect').pipe(mergeMap(connection => { return this.getToken().pipe(map(newToken => { connection.token = newToken; this.saveSessionToken(connection); return connection; })); })); })); } return this.post(body, 'connect').pipe(map(connection => { this.saveSessionToken(connection); return connection; })); } } /** @nocollapse */ FacebookOAuthService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: FacebookOAuthService, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); /** @nocollapse */ FacebookOAuthService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: FacebookOAuthService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: FacebookOAuthService, decorators: [{ type: Injectable }] }); /** * view service for drupal using push_notifications module * @see https://www.drupal.org/project/push_notifications */ class PushNotificationsSerivce extends MainService { constructor() { super(...arguments); this.entityType = 'push_notifications'; } /** * create/register new device with a token * @param pushNotifications notification object to register */ create(pushNotifications) { return this.post(pushNotifications); } /** * delete a subscription by device token * @param token token of the device to be deleted */ delete_push(token) { return this.delete(token); } } /** @nocollapse */ PushNotificationsSerivce.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: PushNotificationsSerivce, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); /** @nocollapse */ PushNotificationsSerivce.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: PushNotificationsSerivce }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: PushNotificationsSerivce, decorators: [{ type: Injectable }] }); /** * angular imports */ /** * implement APP_INITIALIZER * @param systemService system service to connect * @see https://gillespie59.github.io/2016/12/04/angular2-code-before-rendering.html */ function init(systemService) { return () => { const connectionObservable = systemService.connect(true).toPromise(); return connectionObservable; }; } /** * main services module with providers * if you do not need to import all the services you need to make your own module and import the required providers only * ngx-cookie package is required * @see https://www.npmjs.com/package/ngx-cookie */ // @dynamic class Drupal7ServicesModule { } /** @nocollapse */ Drupal7ServicesModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: Drupal7ServicesModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); /** @nocollapse */ Drupal7ServicesModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "14.2.4", ngImport: i0, type: Drupal7ServicesModule, imports: [HttpClientModule] }); /** @nocollapse */ Drupal7ServicesModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: Drupal7ServicesModule, providers: [ MainService, SystemService, UserService, NodeService, FileService, CommentService, TaxonomyTermService, TaxonomyVocabularyService, ViewService, EntityService, MenuService, FacebookOAuthService, PushNotificationsSerivce, { 'provide': APP_INITIALIZER, 'useFactory': init, 'deps': [SystemService], 'multi': true } ], imports: [HttpClientModule] }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.2.4", ngImport: i0, type: Drupal7ServicesModule, decorators: [{ type: NgModule, args: [{ imports: [ HttpClientModule, ], providers: [ MainService, SystemService, UserService, NodeService, FileService, CommentService, TaxonomyTermService, TaxonomyVocabularyService, ViewService, EntityService, MenuService, FacebookOAuthService, PushNotificationsSerivce, { 'provide': APP_INITIALIZER, 'useFactory': init, 'deps': [SystemService], 'multi': true } ], }] }] }); /* * Public API Surface of ngx-drupal7-services */ /** * Generated bundle index. Do not edit. */ export { CommentService, Drupal7ServicesModule, DrupalConstants, EntityService, FacebookOAuthService, FileService, MainService, MenuService, NodeService, PushNotificationsSerivce, SystemService, TaxonomyTermService, TaxonomyVocabularyService, UserService, ViewService, init }; //# sourceMappingURL=ngx-drupal7-services.mjs.map