UNPKG

ngx-drupal8-rest

Version:

> A wrapper library to connect to a Drupal8+ based backend

1,514 lines 53.1 kB
import * as i0 from '@angular/core';
import { PLATFORM_ID, Inject, Injectable, APP_INITIALIZER, NgModule } from '@angular/core';
import * as i1 from '@angular/common/http';
import { HttpClientModule } from '@angular/common/http';
import { Subject, throwError } from 'rxjs';
import { tap, mergeMap, timeout, map, catchError } from 'rxjs/operators';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';

// @dynamic
class DrupalConstants {
    // Singletons
    static instance;
    // props
    settings;
    connection;
    token;
    tokenInit = false;
    /**
     * Init the module with Drupal 8 website configs
     * @param settings Drupal 8 back-end config
     */
    static init(settings) {
        // Optional config default values
        if (!settings.requestTimeout) {
            // 10 seconds
            settings.requestTimeout = 10000;
        }
        if (!settings.cookieLifetime) {
            // 23 days
            settings.cookieLifetime = 2000000;
        }
        this.Instance.settings = settings;
    }
    static get Token() {
        return this.Instance.token;
    }
    static set Token(value) {
        this.Instance.tokenInit = value ? true : false;
        this.Instance.token = value;
    }
    static get TokenInit() {
        return this.Instance.tokenInit;
    }
    static set TokenInit(value) {
        this.Instance.tokenInit = value;
    }
    /**
     * Get the settings object, Supports dynamic config
     */
    static get Settings() {
        if (!this.Instance.settings) {
            throw new Error('ngx-drupal8-rest: Application settings are not set, Please read README.MD file');
        }
        return this.Instance.settings;
    }
    /**
     * Get the back-end structured url
     */
    static get backEndUrl() {
        const settings = this.Settings;
        // Add protocol
        const url = settings.protocol + '://' + settings.host;
        // Check for port and return
        return settings.port ? url + ':' + settings.port : url;
    }
    /**
     * Get Singleton instance
     */
    static get Instance() {
        if (!this.instance) {
            this.instance = new DrupalConstants();
        }
        return this.instance;
    }
    /**
     * Set the current connection info
     */
    static set Connection(newConnection) {
        this.Instance.connection = newConnection;
    }
    /**
     * Get current connection info
     */
    static get Connection() {
        return this.Instance.connection;
    }
}

// Shared

class BaseService {
    httpClient;
    platform;
    static currentTokenRequest = null;
    constructor(httpClient, platform) {
        this.httpClient = httpClient;
        this.platform = platform;
    }
    getToken() {
        if (BaseService.currentTokenRequest) {
            return BaseService.currentTokenRequest.asObservable();
        }
        BaseService.currentTokenRequest = new Subject();
        const tokenOptions = {
            method: 'get',
            responseType: 'text',
        };
        this.request(tokenOptions, '/session/token')
            .pipe(tap((token) => {
            if (DrupalConstants.Token && token !== DrupalConstants.Token) {
                this.deleteConnection();
            }
            DrupalConstants.Token = token;
            if (isPlatformBrowser(this.platform)) {
                localStorage.setItem('token', token);
            }
            // If connection is not init but localstorage contains a connection
            if (!DrupalConstants.Connection && this.connection) {
                DrupalConstants.Connection = this.connection;
            }
            return token;
        }))
            .subscribe({
            next: (token) => {
                queueMicrotask(() => {
                    BaseService.currentTokenRequest.next(token);
                    BaseService.currentTokenRequest.complete();
                    BaseService.currentTokenRequest = null;
                });
            },
            error: (error) => {
                BaseService.currentTokenRequest = null;
                throw Error(error);
            },
        });
        return BaseService.currentTokenRequest.asObservable();
    }
    /**
     * Check for current user if logged in or not.
     * Based on current connection and expiration date
     */
    get isLoggedIn() {
        // if the connection expired, delete the connection
        if (this.connectionExpired) {
            this.deleteConnection();
            return false;
        }
        return DrupalConstants.Connection || this.connection ? true : false;
    }
    /**
     * Get current user login connection
     */
    get connection() {
        if (!isPlatformServer(this.platform)) {
            if (DrupalConstants.Connection) {
                return DrupalConstants.Connection;
            }
            const storageToken = localStorage.getItem('token');
            if (storageToken) {
                DrupalConstants.Token = localStorage.getItem('token');
            }
            // get connection from localstorage
            const connection = (JSON.parse(localStorage.getItem('connection')));
            if (connection) {
                DrupalConstants.Connection = connection;
            }
            // parse and return the data
            return connection;
        }
    }
    /**
     * Check if the current connection is expired
     */
    get connectionExpired() {
        if (!isPlatformServer(this.platform)) {
            // get expiration time in ms
            const expiration = +localStorage.getItem('expiration');
            // get current date
            const now = new Date();
            return expiration ? now.getTime() > expiration : true;
        }
    }
    /**
     * save the user login connection in localstorage and constants singleton
     * @param data connection to be saved
     */
    saveConnection(data, token) {
        if (!isPlatformServer(this.platform)) {
            // set the current session
            DrupalConstants.Connection = data;
            DrupalConstants.Token = token;
            // save the connection in localstorage
            localStorage.setItem('connection', JSON.stringify(data));
            // get current time in ms
            const now = new Date().getTime();
            // get the future expiration time in ms
            const expiration = now + DrupalConstants.Settings.cookieLifetime * 1000;
            // set the expiration time
            localStorage.setItem('expiration', expiration.toString());
            localStorage.setItem('token', token);
        }
    }
    /**
     * remove the current session details
     */
    deleteConnection() {
        if (!isPlatformServer(this.platform)) {
            // empty current session
            DrupalConstants.Connection = undefined;
            DrupalConstants.Token = undefined;
            // removed saved data
            localStorage.removeItem('connection');
            localStorage.removeItem('expiration');
            localStorage.removeItem('token');
        }
    }
    /**
     * Main method for implementing all the HttpClient requests and return the results
     * @param options Custom HttpOptions to be overrided
     * @param resource The resource url, Token frags will be replaced from options.frags, EX: {'/user/{uid}'}
     * @param body the content to be sent with the request, Only for patch and post methods
     */
    request(options, resource, body) {
        // Get full url
        const structuredResource = this.structureResource(resource, options.frags);
        let request;
        // Init http options
        const httpOptions = this.httpOptions(options);
        // Use the desired method
        if (options.method === 'patch' || options.method === 'post') {
            request = this.httpClient[options.method](structuredResource, body, httpOptions);
        }
        else {
            request = this.httpClient[options.method](structuredResource, httpOptions);
        }
        if (resource !== '/session/token' && !DrupalConstants.TokenInit) {
            return this.getToken().pipe(mergeMap(() => request.pipe(timeout(DrupalConstants.Settings.requestTimeout))));
        }
        // Set requests time out from drupal config
        return request.pipe(timeout(DrupalConstants.Settings.requestTimeout));
    }
    /**
     * Get default HttpOptions or replace the custom ones.
     * Supports url params, responseType, headers, observer
     * @param options Custom httpOptions to override the defaults
     */
    httpOptions(options) {
        // Init default options
        const httpOptions = {
            reportProgress: true, // allow for progress
            withCredentials: true,
            responseType: 'json',
            params: {
                _format: 'json', // required by drupal 8 rest
            },
            headers: {},
            observe: 'body',
        };
        // If the user is logged in, add the CSRF header token
        if (DrupalConstants.Connection && DrupalConstants.Connection.csrf_token) {
            httpOptions.headers['X-CSRF-Token'] =
                DrupalConstants.Connection.csrf_token;
        }
        else if (DrupalConstants.Token) {
            httpOptions.headers['X-CSRF-Token'] = DrupalConstants.Token;
        }
        // Override defaults
        if (options.params) {
            httpOptions.params = options.params;
        }
        if (options.responseType) {
            httpOptions.responseType = options.responseType;
        }
        if (options.headers) {
            httpOptions.headers = options.headers;
        }
        if (options.observe) {
            httpOptions.observe = options.observe;
        }
        return httpOptions;
    }
    /**
     * get full resource structure after adding the frags
     * @param resource drupal base resource url
     * @param frags frags to change it with the value that inside brackets
     */
    structureResource(resource, frags = []) {
        // if there is no custom frags
        if (frags.length === 0) {
            return DrupalConstants.backEndUrl + resource;
        }
        // split the resource to fragments
        const resourceParts = resource.split('/');
        // init empty string
        let resourceFrags = '';
        // check for each frag and replace it
        resourceParts.forEach((part, index) => {
            // if the part is a frag
            if (part[0] === '{') {
                // get the value from frags array and remove it
                resourceFrags += `/${frags.shift()}`;
            }
            else {
                // if part is not a frag add it directly
                resourceFrags += `/${part}`;
            }
        });
        // remove duplicate / at the start of the resource
        resourceFrags = resourceFrags.substr(1);
        return DrupalConstants.backEndUrl + resourceFrags;
    }
    /** @nocollapse */ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: BaseService, deps: [{ token: i1.HttpClient }, { token: PLATFORM_ID }], target: i0.ɵɵFactoryTarget.Injectable });
    /** @nocollapse */ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: BaseService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: BaseService, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: i1.HttpClient }, { type: undefined, decorators: [{
                    type: Inject,
                    args: [PLATFORM_ID]
                }] }] });

class UserService extends BaseService {
    static keyStoreCredentials = 'drx_8_derc';
    /**
     * Implements resource /user/login POST
     * Logs the user in using cookie authentication method
     * @param credentials username and password object style of the user
     */
    login(credentials) {
        const httpOptions = {
            method: 'post',
        };
        return this.request(httpOptions, '/user/login', credentials).pipe(mergeMap((response) => {
            this.saveCredentialsInStorage(credentials);
            return this.getToken().pipe(map((token) => {
                // Save the response connection
                this.saveConnection(response, token);
                return response;
            }));
        }));
    }
    /**
     * Implements /user/logout POST
     * Logs the user out.
     * Will throw and error if the user is not logged in
     */
    logout() {
        // if the user is not logged in yet, throw an observable error
        if (!this.isLoggedIn) {
            return throwError(() => 'User is not logged in.');
        }
        // set the options and logout token
        const httpOptions = {
            method: 'post',
            params: {
                _format: 'json',
                token: this.connection.logout_token,
            },
        };
        // delete the saved connection after logging out
        return this.request(httpOptions, '/user/logout').pipe(tap(this.deleteConnection), tap(this.deleteStoredCredentials), catchError((err) => {
            if (err && err.status === 403) {
                this.deleteConnection();
            }
            throw err;
        }));
    }
    /**
     * Implement resource /user/{user} GET
     * @param uid the user id
     */
    get(uid) {
        const httpOptions = {
            method: 'get',
            frags: [uid],
        };
        return this.request(httpOptions, '/user/{user}');
    }
    /**
     * Implement resource /entity/user: POST
     * @param user user object to create
     */
    create(user) {
        const httpOptions = {
            method: 'post',
        };
        return this.request(httpOptions, '/entity/user', user);
    }
    /**
     * Implement resource /user/{user}: PATCH
     * @param uid user id to update
     * @param user user object with required values
     */
    update(uid, user) {
        const httpOptions = {
            method: 'patch',
            frags: [uid],
        };
        return this.request(httpOptions, '/user/{user}', user);
    }
    /**
     * Implement resource /user/{user}: DELETE
     * @param uid user id to delete
     */
    delete(uid) {
        const httpOptions = {
            method: 'delete',
            frags: [uid],
        };
        return this.request(httpOptions, '/user/{user}');
    }
    /**
     * Implement resource /user/register: POST
     * @param user user info object to register
     */
    register(user) {
        const httpOptions = {
            method: 'post',
        };
        return this.request(httpOptions, '/user/register', user);
    }
    /**
     * try to login user with the saved credentials in local storage if they exist
     * @returns Observable<LoginResponse>
     */
    attemptToLoginWithSavedCredentials() {
        const credentials = this.getStoredCredentials();
        if (!credentials) {
            return throwError(() => 'No credentials stored');
        }
        return this.login(credentials);
    }
    /**
     * Delete credentials from localstorage
     */
    deleteStoredCredentials() {
        localStorage.removeItem(UserService.keyStoreCredentials);
    }
    /**
     * Get the current user credentials from localstorage
     */
    getStoredCredentials() {
        const credStore = localStorage.getItem(UserService.keyStoreCredentials);
        if (!credStore) {
            return null;
        }
        return JSON.parse(credStore);
    }
    /**
     * Save credentials in localstorage
     * @param credentials credentials to save in localstorage
     */
    saveCredentialsInStorage(credentials) {
        localStorage.setItem(UserService.keyStoreCredentials, JSON.stringify(credentials));
    }
    /** @nocollapse */ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: UserService, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
    /** @nocollapse */ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: UserService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: UserService, decorators: [{
            type: Injectable
        }] });

class ViewService extends BaseService {
    /**
     * Implements /entity/view/{view}: GET
     * Get view result
     * @param machineName view machine name
     */
    getView(machineName) {
        const httpOptions = {
            method: 'get',
            frags: [machineName],
        };
        return this.request(httpOptions, '/entity/view/{view}');
    }
    /**
     * Implements Views rest export
     * Returns array of view rows
     * @param viewPath the view url path, EX: '/view/my_custom_view_path'
     */
    get(viewPath, viewOptions = {}) {
        const httpOptions = {
            method: 'get',
            params: {
                '_format': 'json'
            }
        };
        if (viewOptions.args) {
            viewPath += '/' + viewOptions.args.join('/');
        }
        if (viewOptions.filters) {
            httpOptions.params = { ...httpOptions.params, ...viewOptions.filters };
        }
        if (viewOptions.pagination) {
            httpOptions.params = { ...httpOptions.params, ...viewOptions.pagination };
        }
        if (viewOptions.sorting) {
            httpOptions.params = { ...httpOptions.params, ...viewOptions.sorting };
        }
        return this.request(httpOptions, viewPath);
    }
    /** @nocollapse */ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: ViewService, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
    /** @nocollapse */ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: ViewService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: ViewService, decorators: [{
            type: Injectable
        }] });

class ContentService extends BaseService {
    /**
     * Implement resource /node/{node} GET
     * @param nid the node id
     */
    get(nid) {
        const httpOptions = {
            method: 'get',
            frags: [nid]
        };
        return this.request(httpOptions, '/node/{node}');
    }
    /**
     * Implement resource /node: POST
     * @param content node object to create
     */
    create(content) {
        const httpOptions = {
            method: 'post',
        };
        return this.request(httpOptions, '/node', content);
    }
    /**
     * Implement resource /node/{node}: PATCH
     * @param nid node id to update
     * @param content node object with required values
     */
    update(nid, content) {
        const httpOptions = {
            method: 'patch',
            frags: [nid]
        };
        return this.request(httpOptions, '/node/{node}', content);
    }
    /**
     * Implement resource /node/{node}: DELETE
     * @param nid content id to delete
     */
    delete(nid) {
        const httpOptions = {
            method: 'delete',
            frags: [nid]
        };
        return this.request(httpOptions, '/node/{node}');
    }
    /**
     * Implement resource /entity/node_type/{node_type}
     * @param type node type or machine name like page, article
     */
    contentType(type) {
        const httpOptions = {
            method: 'get',
            frags: [type]
        };
        return this.request(httpOptions, '/entity/node_type/{node_type}');
    }
    /** @nocollapse */ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: ContentService, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
    /** @nocollapse */ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: ContentService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: ContentService, decorators: [{
            type: Injectable
        }] });

class TaxonomyService extends BaseService {
    /**
     * Implement resource /taxonomy/term/{taxonomy_term} GET
     * @param tid the term id
     */
    get(tid) {
        const httpOptions = {
            method: 'get',
            frags: [tid]
        };
        return this.request(httpOptions, '/taxonomy/term/{taxonomy_term}');
    }
    /**
     * Implement resource /taxonomy/term: POST
     * @param term term object to create
     */
    create(term) {
        const httpOptions = {
            method: 'post',
        };
        return this.request(httpOptions, '/taxonomy/term', term);
    }
    /**
     * Implement resource /taxonomy/term/{taxonomy_term}: PATCH
     * @param tid node id to update
     * @param term term object with required values
     */
    update(tid, term) {
        const httpOptions = {
            method: 'patch',
            frags: [tid]
        };
        return this.request(httpOptions, '/taxonomy/term/{taxonomy_term}', term);
    }
    /**
     * Implement resource /taxonomy/term/{taxonomy_term}: DELETE
     * @param tid term id to delete
     */
    delete(tid) {
        const httpOptions = {
            method: 'delete',
            frags: [tid]
        };
        return this.request(httpOptions, '/taxonomy/term/{taxonomy_term}');
    }
    /**
     * Implement /entity/taxonomy_vocabulary/{taxonomy_vocabulary}: Get
     * @param machineName vocabulary machine name like tags
     */
    vocabulary(machineName) {
        const httpOptions = {
            method: 'get',
            frags: [machineName]
        };
        return this.request(httpOptions, '/entity/taxonomy_vocabulary/{taxonomy_vocabulary}');
    }
    /** @nocollapse */ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: TaxonomyService, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
    /** @nocollapse */ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: TaxonomyService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: TaxonomyService, decorators: [{
            type: Injectable
        }] });

class FileService extends BaseService {
    /**
     * Implement resource /entity/file/{file}: GET
     * @param fid the file id
     */
    get(fid) {
        const httpOptions = {
            method: 'get',
            frags: [fid]
        };
        return this.request(httpOptions, '/entity/file/{file}');
    }
    /**
     * Implement resource /file/upload/{entity_type_id}/{bundle}/{field_name}: POST
     * @param file the file to create
     */
    upload(entityType, bundle, fieldName, file) {
        const httpOptions = {
            method: 'post',
            frags: [entityType, bundle, fieldName],
            headers: {
                'Content-Type': 'application/octet-stream',
                'Content-Disposition': `file; filename="${file.name}"`
            },
        };
        // If the user is logged in, add the CSRF header token
        if (DrupalConstants.Connection && DrupalConstants.Connection.csrf_token) {
            httpOptions.headers['X-CSRF-Token'] = DrupalConstants.Connection.csrf_token;
        }
        return this.request(httpOptions, '/file/upload/{entity_type_id}/{bundle}/{field_name}', file);
    }
    /**
     * Implement resource /entity/file/{file}: PATCH
     * @param fid the file id
     * @param file the file content to be updated
     */
    update(fid, file) {
        const httpOptions = {
            method: 'patch',
            frags: [fid],
        };
        return this.request(httpOptions, '/entity/file/{file}', file);
    }
    /**
     * Implement resource /entity/file/{file}: DELETE
     * @param fid the file id
     */
    delete(fid) {
        const httpOptions = {
            method: 'delete',
            frags: [fid],
        };
        return this.request(httpOptions, '/entity/file/{file}');
    }
    /** @nocollapse */ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: FileService, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
    /** @nocollapse */ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: FileService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: FileService, decorators: [{
            type: Injectable
        }] });

class MediaService extends BaseService {
    /**
     * Implement resource /media/{media}/edit GET
     * @param mid the media id
     */
    get(mid) {
        const httpOptions = {
            method: 'get',
            frags: [mid]
        };
        return this.request(httpOptions, '/media/{media}/edit');
    }
    /**
     * Implement resource /entity/media: POST
     * @param media media object to create
     */
    create(media) {
        const httpOptions = {
            method: 'post',
        };
        return this.request(httpOptions, '/entity/media', media);
    }
    /**
     * Implement resource /media/{media}/edit: PATCH
     * @param mid media id to update
     * @param media media object with required values
     */
    update(mid, media) {
        const httpOptions = {
            method: 'patch',
            frags: [mid]
        };
        return this.request(httpOptions, '/media/{media}/edit', media);
    }
    /**
     * Implement resource /media/{media}/edit: DELETE
     * @param mid media id to delete
     */
    delete(mid) {
        const httpOptions = {
            method: 'delete',
            frags: [mid]
        };
        return this.request(httpOptions, '/media/{media}/edit');
    }
    /**
     * Implement resource /entity/media_type/{media_type}
     * @param type media type or machine name like audio, image and video
     */
    mediaType(type) {
        const httpOptions = {
            method: 'get',
            frags: [type]
        };
        return this.request(httpOptions, '/entity/media_type/{media_type}');
    }
    /** @nocollapse */ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: MediaService, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
    /** @nocollapse */ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: MediaService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: MediaService, decorators: [{
            type: Injectable
        }] });

class FlagService extends BaseService {
    /**
     * Implement resource /entity/flagging/{flagging}: GET
     * @param fid the flag id
     */
    get(fid) {
        const httpOptions = {
            method: 'get',
            frags: [fid]
        };
        return this.request(httpOptions, '/entity/flagging/{flagging}');
    }
    /**
     * Implement resource /entity/flagging: POST
     * @param flag: flag content
     */
    post(flag) {
        const httpOptions = {
            method: 'post',
        };
        return this.request(httpOptions, '/entity/flagging', flag);
    }
    update(fid, flag) {
        const httpOptions = {
            method: 'patch',
            frags: [fid]
        };
        return this.request(httpOptions, '/entity/flagging/{flagging}', flag);
    }
    delete(fid) {
        const httpOptions = {
            method: 'delete',
            frags: [fid]
        };
        return this.request(httpOptions, '/entity/flagging/{flagging}');
    }
    /** @nocollapse */ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: FlagService, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
    /** @nocollapse */ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: FlagService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: FlagService, decorators: [{
            type: Injectable
        }] });

class WebformService extends BaseService {
    /**
     * Implement resource 	/webform/{webform} GET
     * @param name the webform machine name
     * @param langCode the language code for the webform
     */
    get(machineName, langCode) {
        const httpOptions = {
            method: 'get',
            frags: [machineName],
        };
        if (langCode) {
            httpOptions.params = { langcode: langCode };
        }
        return this.request(httpOptions, '/webform/{webform}');
    }
    /**
     * Implement resource /webform_rest/{webform_id}/fields GET
     * @param machineName the webform machine name
     * @param langCode the language code for the webform
     */
    fields(machineName, langCode) {
        const httpOptions = {
            method: 'get',
            frags: [machineName],
        };
        if (langCode) {
            httpOptions.params = { langcode: langCode };
        }
        return this.request(httpOptions, '/webform_rest/{webform_id}/fields');
    }
    /**
     * Implement resource /webform_rest/{webform_id}/submission/{sid} GET
     * @param machineName the webform machine name
     * @param sid the webform submittion id
     */
    getSubmission(machineName, sid, langCode) {
        const httpOptions = {
            method: 'get',
            frags: [machineName, sid.toString()],
        };
        if (langCode) {
            httpOptions.params = { langcode: langCode };
        }
        return this.request(httpOptions, '/webform_rest/{webform_id}/submission/{sid}');
    }
    /**
     * Implement resource /webform_rest/{webform_id}/submission/{sid} PATCH
     * @param machineName the webform machine name
     * @param sid the webform submittion id
     * @param webformSubmission the submission content object of fields
     */
    updateSubmission(machineName, sid, webformSubmission) {
        const httpOptions = {
            method: 'patch',
            frags: [machineName, sid.toString()],
        };
        return this.request(httpOptions, '/webform_rest/{webform_id}/submission/{sid}', webformSubmission);
    }
    /**
     * Implement resource /webform_rest/submit POST
     * @param webformSubmission the submission content object of fields
     * All required fields should be added or the request will return error 400 :/
     */
    submit(webformSubmission) {
        const httpOptions = {
            method: 'post',
        };
        return this.request(httpOptions, '/webform_rest/submit', webformSubmission);
    }
    /**
     * Implement resource /webform_rest/{webform_id}/upload/{field_name}: POST
     * @param file the file to upload
     */
    upload(machineName, fieldName, file) {
        const httpOptions = {
            method: 'post',
            frags: [machineName, fieldName],
            headers: {
                'Content-Type': 'application/octet-stream',
                'Content-Disposition': `file; filename="${file.name}"`,
            },
        };
        // If the user is logged in, add the CSRF header token
        if (DrupalConstants.Connection && DrupalConstants.Connection.csrf_token) {
            httpOptions.headers['X-CSRF-Token'] =
                DrupalConstants.Connection.csrf_token;
        }
        return this.request(httpOptions, '/webform_rest/{webform_id}/upload/{field_name}', file);
    }
    /** @nocollapse */ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: WebformService, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
    /** @nocollapse */ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: WebformService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: WebformService, decorators: [{
            type: Injectable
        }] });

class PushService extends BaseService {
    register(registration) {
        const httpOptions = {
            method: 'post',
        };
        return this.request(httpOptions, '/entity/push_notifications_token', registration);
    }
    get(tokenId) {
        const httpOptions = {
            method: 'get',
            frags: [tokenId]
        };
        return this.request(httpOptions, '/push_notifications/token/{push_notifications_token}');
    }
    update(tokenId, registration) {
        const httpOptions = {
            method: 'patch',
            frags: [tokenId]
        };
        return this.request(httpOptions, '/push_notifications/token/{push_notifications_token}', registration);
    }
    delete(tokenId) {
        const httpOptions = {
            method: 'delete',
            frags: [tokenId]
        };
        return this.request(httpOptions, '/push_notifications/token/{push_notifications_token}');
    }
    /** @nocollapse */ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: PushService, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
    /** @nocollapse */ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: PushService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: PushService, decorators: [{
            type: Injectable
        }] });

class CommerceService extends BaseService {
    // Commerce Cart API
    getCart() {
        const httpOptions = {
            method: 'get',
        };
        return this.request(httpOptions, '/cart');
    }
    getCartOrder(orderId) {
        const httpOptions = {
            method: 'get',
            frags: [orderId],
        };
        return this.request(httpOptions, '/cart/{order}');
    }
    addToCart(data) {
        const httpOptions = {
            method: 'post',
        };
        return this.request(httpOptions, '/cart/add', data);
    }
    updateCartOrderItems(orderId, items) {
        const httpOptions = {
            method: 'patch',
            frags: [orderId],
        };
        return this.request(httpOptions, '/cart/{order}/items', items);
    }
    deleteCartOrderItem(orderId, itemId) {
        const httpOptions = {
            method: 'delete',
            frags: [orderId, itemId],
        };
        return this.request(httpOptions, '/cart/{order}/items/{item}');
    }
    deleteCartOrderItems(orderId) {
        const httpOptions = {
            method: 'delete',
            frags: [orderId],
        };
        return this.request(httpOptions, '/cart/{order}/items');
    }
    // Commerce Decoupled Checkout
    createOrder(order) {
        const httpOptions = {
            method: 'post',
        };
        return this.request(httpOptions, '/commerce/order/create', order);
    }
    createPayment(orderId, payment) {
        const httpOptions = {
            method: 'post',
            frags: [orderId],
        };
        return this.request(httpOptions, '/commerce/payment/create/{order_id}', payment);
    }
    capturePayment(orderId, paymenId) {
        const httpOptions = {
            method: 'post',
            frags: [orderId, paymenId],
        };
        return this.request(httpOptions, '/commerce/payment/capture/{order_id}/{payment_id}', {});
    }
    /** @nocollapse */ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: CommerceService, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
    /** @nocollapse */ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: CommerceService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: CommerceService, decorators: [{
            type: Injectable
        }] });

class CommentService extends BaseService {
    create(comment) {
        const httpOptions = {
            method: 'post',
        };
        return this.request(httpOptions, '/comment', comment);
    }
    update(cid, comment) {
        const httpOptions = {
            method: 'patch',
            frags: [cid],
        };
        return this.request(httpOptions, '/comment/{comment}', comment);
    }
    delete(cid) {
        const httpOptions = {
            method: 'delete',
            frags: [cid],
        };
        return this.request(httpOptions, '/comment/{comment}');
    }
    getById(cid) {
        const httpOptions = {
            method: 'get',
            frags: [cid],
        };
        return this.request(httpOptions, '/comment/{comment}');
    }
    getType(type) {
        const httpOptions = {
            method: 'get',
            frags: [type],
        };
        return this.request(httpOptions, '/entity/comment_type/{comment_type}');
    }
    /** @nocollapse */ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: CommentService, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
    /** @nocollapse */ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: CommentService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: CommentService, decorators: [{
            type: Injectable
        }] });

class QuizService extends BaseService {
    /**
     * Implements /quiz/{quiz}: GET
     * Returns quiz entity
     * @param qid the quiz entity ID
     */
    get(qid) {
        const httpOptions = {
            method: 'get',
            params: {
                _format: 'json',
            },
            frags: [qid],
        };
        return this.request(httpOptions, '/quiz/{quiz}');
    }
    /**
     * Implements /entity/quiz: POST
     * Returns quiz created entity
     * @param quiz the quiz entity with updated values
     */
    create(quiz) {
        const httpOptions = {
            method: 'post',
            params: {
                _format: 'json',
            },
        };
        return this.request(httpOptions, '/entity/quiz', quiz);
    }
    /**
     * Implements /quiz/{quiz}: PATCH
     * Returns quiz updated entity
     * @param qid the quiz entity ID
     * @param quiz the quiz entity with updated values
     */
    update(qid, quiz) {
        const httpOptions = {
            method: 'patch',
            params: {
                _format: 'json',
            },
            frags: [qid],
        };
        return this.request(httpOptions, '/quiz/{quiz}', quiz);
    }
    /**
     * Implements /quiz/{quiz}: DELETE
     * @param qid the quiz entity ID
     */
    delete(qid) {
        const httpOptions = {
            method: 'delete',
            params: {
                _format: 'json',
            },
            frags: [qid],
        };
        return this.request(httpOptions, '/quiz/{quiz}');
    }
    /**
     * Implements /entity/quiz_type/{quiz_type}: GET
     * Returns quiz type
     * @param quizMachineName the quiz type machine name
     */
    getType(quizMachineName) {
        const httpOptions = {
            method: 'get',
            params: {
                _format: 'json',
            },
            frags: [quizMachineName],
        };
        return this.request(httpOptions, '/entity/quiz_type/{quiz_type}');
    }
    /**
     * Implements /entity/quiz_feedback_type/{quiz_feedback_type}: GET
     * Returns quiz feedback type
     * @param feedbackMachineName the feedback type machine name
     */
    getFeedbackType(feedbackMachineName) {
        const httpOptions = {
            method: 'get',
            params: {
                _format: 'json',
            },
            frags: [feedbackMachineName],
        };
        return this.request(httpOptions, '/entity/quiz_feedback_type/{quiz_feedback_type}');
    }
    // Question
    /**
     * Implements /quiz-question/{quiz_question}: GET
     * Returns quiz question entity
     * @param qqid the quiz question entity ID
     */
    getQuestion(qqid) {
        const httpOptions = {
            method: 'get',
            params: {
                _format: 'json',
            },
            frags: [qqid],
        };
        return this.request(httpOptions, '/quiz-question/{quiz_question}');
    }
    /**
     * Implements /entity/quiz_question: POST
     * Returns question created entity
     * @param question the quiz question entity to create
     */
    createQuestion(question) {
        const httpOptions = {
            method: 'post',
            params: {
                _format: 'json',
            },
        };
        return this.request(httpOptions, '/entity/quiz_question', question);
    }
    /**
     * Implements /quiz-question/{quiz_question}: PATCH
     * Returns question updated entity
     * @param qqid the quiz question entity ID
     * @param question the quiz question entity with updated values
     */
    updateQuestion(qqid, question) {
        const httpOptions = {
            method: 'patch',
            params: {
                _format: 'json',
            },
            frags: [qqid],
        };
        return this.request(httpOptions, '/quiz-question/{quiz_question}', question);
    }
    /**
     * Implements /quiz-question/{quiz_question}: DELETE
     * @param qqid the question entity ID
     */
    deleteQuestion(qqid) {
        const httpOptions = {
            method: 'delete',
            params: {
                _format: 'json',
            },
            frags: [qqid],
        };
        return this.request(httpOptions, '/quiz-question/{quiz_question}');
    }
    /**
     * Implements /entity/quiz_question_type/{quiz_question_type}: GET
     * Returns quiz question type
     * @param feedbackMachineName the type machine name
     */
    getQuestionType(typeMachineName) {
        const httpOptions = {
            method: 'get',
            params: {
                _format: 'json',
            },
            frags: [typeMachineName],
        };
        return this.request(httpOptions, '/entity/quiz_question_type/{quiz_question_type}');
    }
    // Relationship
    /**
     * Implements /quiz-question-relationship/{quiz_question_relationship}: GET
     * Returns quiz question relationship entity
     * @param qqrid the quiz question relationship entity ID 'question id'
     */
    getQuestionRelationship(qqrid) {
        const httpOptions = {
            method: 'get',
            params: {
                _format: 'json',
            },
            frags: [qqrid],
        };
        return this.request(httpOptions, '/quiz-question-relationship/{quiz_question_relationship}');
    }
    /**
     * Implements /quiz-question-relationship/{quiz_question_relationship}: POST
     * Returns quiz question relationship created entity
     * @param questionRelationship the quiz question relationship entity to create
     */
    createQuestionRelationship(questionRelationship) {
        const httpOptions = {
            method: 'post',
            params: {
                _format: 'json',
            },
        };
        return this.request(httpOptions, '/entity/quiz_question_relationship', questionRelationship);
    }
    /**
     * Implements /quiz-question-relationship/{quiz_question_relationship}: PATCH
     * Returns quiz question relationship updated entity
     * @param qqrid the quiz question relationship entity ID 'question id'
     * @param questionRelationship the quiz question relationship updated entity
     */
    updateQuestionRelationship(qqrid, questionRelationship) {
        const httpOptions = {
            method: 'patch',
            params: {
                _format: 'json',
            },
            frags: [qqrid],
        };
        return this.request(httpOptions, '/quiz-question-relationship/{quiz_question_relationship}', questionRelationship);
    }
    /**
     * Implements /quiz-question-relationship/{quiz_question_relationship}: DELETE
     * @param qqrid the quiz question relationship entity ID 'question id'
     */
    deleteQuestionRelationship(qqrid) {
        const httpOptions = {
            method: 'delete',
            params: {
                _format: 'json',
            },
            frags: [qqrid],
        };
        return this.request(httpOptions, '/quiz-question-relationship/{quiz_question_relationship}');
    }
    // Result
    /**
     * Implements /quiz/{quiz}/result/{quiz_result}: GET
     * Returns quiz result entity
     * @param qid the quiz entity ID
     * @param qrid the quiz result entity ID
     */
    getResult(qid, qrid) {
        const httpOptions = {
            method: 'get',
            params: {
                _format: 'json',
            },
            frags: [qid, qrid],
        };
        return this.request(httpOptions, '/quiz/{quiz}/result/{quiz_result}');
    }
    /**
     * Implements /entity/quiz_result: POST
     * Returns quiz result created entity
     * @param result the quiz result entity
     */
    createResult(result) {
        const httpOptions = {
            method: 'post',
            params: {
                _format: 'json',
            },
        };
        return this.request(httpOptions, '/entity/quiz_result', result);
    }
    /**
     * Implements /quiz/{quiz}/result/{quiz_result}: PATCH
     * Returns quiz result updated entity
     * @param qid the quiz entity ID
     * @param qrid the quiz result entity ID
     * @param result the quiz result updated entity
     */
    updateResult(qid, qrid, result) {
        const httpOptions = {
            method: 'patch',
            params: {
                _format: 'json',
            },
            frags: [qid, qrid]
        };
        return this.request(httpOptions, '/quiz/{quiz}/result/{quiz_result}', result);
    }
    /**
     * Implements /quiz/{quiz}/result/{quiz_result}: DELETE
     * @param qid the quiz entity ID
     * @param qrid the quiz result entity ID
     */
    deleteResult(qid, qrid) {
        const httpOptions = {
            method: 'delete',
            params: {
                _format: 'json',
            },
            frags: [qid, qrid]
        };
        return this.request(httpOptions, '/quiz/{quiz}/result/{quiz_result}');
    }
    /**
     * Implements /entity/quiz_result_type/{quiz_result_type}: GET
     * Returns quiz result type
     * @param resultMachineName the type machine name
     */
    getResultType(resultMachineName) {
        const httpOptions = {
            method: 'get',
            params: {
                _format: 'json',
            },
            frags: [resultMachineName],
        };
        return this.request(httpOptions, '/entity/quiz_result_type/{quiz_result_type}');
    }
    // Result answer: interfaces TODO
    /**
     * Implements /quiz/{quiz}/result/{quiz_result}/answer/{quiz_result_answer}: GET
     * Returns quiz result answer entity
     * @param qid the quiz entity ID
     * @param qrid the quiz result entity ID
     * @param qrid the quiz result answer entity ID
     */
    getResultAnswer(qid, qrid, raid) {
        const httpOptions = {
            method: 'get',
            params: {
                _format: 'json',
            },
            frags: [qid, qrid, raid],
        };
        return this.request(httpOptions, '/quiz/{quiz}/result/{quiz_result}/answer/{quiz_result_answer}');
    }
    /**
     * Implements /entity/quiz_result_answer: POST
     * Returns quiz result answer created entity
     * @param answer the quiz result answer entity
     */
    createResultAnswer(answer) {
        const httpOptions = {
            method: 'post',
            params: {
                _format: 'json',
            },
        };
        return this.request(httpOptions, '/entity/quiz_result_answer', answer);
    }
    /**
     * Implements /quiz/{quiz}/result/{quiz_result}/answer/{quiz_result_answer}: PATCH
     * Returns quiz result updated entity
     * Returns quiz result answer entity
     * @param qid the quiz entity ID
     * @param qrid the quiz result entity ID
     * @param qrid the quiz result answer entity ID
     * @param answer the quiz result answer entity
     */
    updateResultAnswer(qid, qrid, raid, answer) {
        const httpOptions = {
            method: 'patch',
            params: {
                _format: 'json',
            },
            frags: [qid, qrid, raid]
        };
        return this.request(httpOptions, '/quiz/{quiz}/result/{quiz_result}/answer/{quiz_result_answer}', answer);
    }
    /**
     * Implements /quiz/{quiz}/result/{quiz_result}/answer/{quiz_result_answer}: DELETE
     * @param qid the quiz entity ID
     * @param qrid the quiz result entity ID
     * @param qrid the quiz result answer entity ID
     */
    deleteResultAnswer(qid, qrid, raid) {
        const httpOptions = {
            method: 'delete',
            params: {
                _format: 'json',
            },
            frags: [qid, qrid, raid]
        };
        return this.request(httpOptions, '/quiz/{quiz}/result/{quiz_result}/answer/{quiz_result_answer}');
    }
    /**
       * Implements /entity/quiz_result_answer_type/{quiz_result_answer_type}: GET
       * Returns quiz answer result type
       * @param resultMachineName the type machine name
       */
    getResultAnswerType(resultAnswerMachineName) {
        const httpOptions = {
            method: 'get',
            params: {
                _format: 'json',
            },
            frags: [resultAnswerMachineName],
        };
        return this.request(httpOptions, '/entity/quiz_result_answer_type/{quiz_result_answer_type}');
    }
    /** @nocollapse */ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: QuizService, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
    /** @nocollapse */ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: QuizService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: QuizService, decorators: [{
            type: Injectable
        }] });

/**
 * implement APP_INITIALIZER
 * @param userService user service
 * @see https://gillespie59.github.io/2016/12/04/angular2-code-before-rendering.html
 */
function init(userService) {
    return () => {
        DrupalConstants.Connection = userService.connection;
    };
}
// @dynamic
class Drupal8RestModule {
    /** @nocollapse */ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: Drupal8RestModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
    /** @nocollapse */ static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.2.7", ngImport: i0, type: Drupal8RestModule, imports: [HttpClientModule] });
    /** @nocollapse */ static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: Drupal8RestModule, providers: [
            BaseService,
            UserService,
            ViewService,
            ContentService,
            TaxonomyService,
            FileService,
            MediaService,
            FlagService,
            WebformService,
            PushService,
            CommerceService,
            CommentService,
            QuizService,
            {
                'provide': APP_INITIALIZER,
                'useFactory': init,
                'deps': [UserService],
                'multi': true
            }
        ], imports: [HttpClientModule] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.7", ngImport: i0, type: Drupal8RestModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [
                        HttpClientModule
                    ],
                    providers: [
                        BaseService,
                        UserService,
                        ViewService,
                        ContentService,
                        TaxonomyService,
                        FileService,
                        MediaService,
                        FlagService,
                        WebformService,
                        PushService,
                        CommerceService,
                        CommentService,
                        QuizService,
                        {
                            'provide': APP_INITIALIZER,
                            'useFactory': init,
                            'deps': [UserService],
                            'multi': true
                        }
                    ]
                }]
        }] });

/*
 * Public API Surface of ngx-drupal8-rest
 */

/**
 * Generated bundle index. Do not edit.
 */

export { BaseService, CommentService, CommerceService, ContentService, Drupal8RestModule, DrupalConstants, FileService, FlagService, MediaService, PushService, QuizService, TaxonomyService, UserService, ViewService, WebformService, init };
//# sourceMappingURL=ngx-drupal8-rest.mjs.map