All files / src/ODataApi ODataApi.ts

100% Statements 50/50
100% Branches 20/20
100% Functions 17/17
100% Lines 50/50
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257                1x 1x               1x                   388x                                           33x                                           17x                                                   9x 9x   5x                     388x 4x                                         9x 9x 4x                                           3x 3x 1x                           89x 89x 89x 89x 89x 63x 26x 25x   1x 1x           1x   88x 85x     88x 1x 1x     88x 13x 13x 3x           1x             13x   75x 60x 60x 11x           4x             60x   15x 15x 1x           1x             15x          
/**
 * @module ODataApi
 */ /** */
 
import { Observable } from 'rxjs/Observable';
import { IContent, ISavedContent, SavedContent } from '../Content';
import { BaseHttpProvider } from '../HttpProviders';
import { BaseRepository } from '../Repository/BaseRepository';
import { ODataHelper } from '../SN';
import { CustomAction, ICustomActionOptions, IODataParams, IODataRequestOptions, ODataCollectionResponse, ODataResponse } from './';
 
/**
 * This class contains methods and classes for sending requests and getting responses from the Content Repository through OData REST API.
 *
 * Following methods return Rxjs Observables which are made from the ajax requests' promises. Action methods like Delete or Rename on Content calls this methods,
 * gets their responses as Observables and returns them so that you can subscribe them in your code.
 */
export class ODataApi<THttpProvider extends BaseHttpProvider> {
 
    /**
     * The HTTP provider instance for making AJAX calls.
     */
 
    /**
     * @param {BaseRepository} repository Reference to a Repository instance
     */
    constructor(
        private readonly _repository: BaseRepository<THttpProvider>,
    ) {
    }
 
    /**
     * Method to get a Content from the Content Repository through OData REST API.
     *
     * @param {ODataRequestOptions} options Object with the params of the ajax request.
     * @param {new(...args): T} returns The content type that will be returned
     * @returns {Observable} Returns an Rxjs observable that you can subscribe of in your code.
     *
     * ```ts
     * myODataApi.Get(new ODataApi.ODataRequestOptions({
     *      path: 'Root/Sites/Default_site/todos'
     *      }), ContentTypes.TaskList)
     *     .subscribe(result=>{
     *          console.log('My TaskList is:', result.d)
     *      });
     * ```
     */
    public Get<T extends IContent>(options: IODataRequestOptions<T>): Observable<ODataResponse<T & ISavedContent>> {
 
        return this._repository.Ajax<ODataResponse<T & ISavedContent>>(`${options.path}?${ODataHelper.buildUrlParamString(this._repository.Config, options.params)}`, 'GET').share();
    }
 
    /**
     * Method to fetch children of a Content from the Content Repository through OData REST API.
     *
     * This method creates an Observable, sends an ajax request to the server and convert the reponse to promise which will be the argument of the Observable.
     * @params options {ODataRequestOptions} Object with the params of the ajax request.
     * @returns {Observable} Returns an Rxjs observable that you can subscribe of in your code.
     *
     * ```ts
     * myODataApi.Fetch(new ODataApi.ODataRequestOptions({
     *       path: 'Root/Sites/Default_site/todos'
     *       }), ContentTypes.Task)
     *   .subscribe(result=>{
     *      console.log('Tasks count:', result.d.__count);
     *      console.log('The Tasks are:', result.d.results);
     *   });
     * ```
     */
    public Fetch<T extends IContent = IContent>(options: IODataRequestOptions<T>): Observable<ODataCollectionResponse<T & ISavedContent>> {
 
        return this._repository.Ajax<ODataCollectionResponse<T & ISavedContent>>(`${options.path}?${ODataHelper.buildUrlParamString(this._repository.Config, options.params)}`, 'GET').share();
    }
 
    /**
     * Method to post a created content into the sense NET Content Repoository.
     * @param {string} path The Path of the content
     * @param {T} content The options (fields) for the content to be created.
     * @param { new(opt, repository):T } postedContentType The type of the content
     * @param {IRepository} repository The repository for the content creation
     * @returns {Observable<T>} An observable whitch will be updated with the created content.
     *
     * ```ts
     *  const myTask = new ContentTypes.Task({
     *       Name: 'My New Task',
     *       DueDate: new Date(),
     *  }, myRepository)
     *
     *  myODataApi.Post('Root/Sites/Default_site/todos', myTask, ContentTypes.Task)
     *  .subscribe(result=>{
     *      console.log('My New Task is:', result);
     *  });
     * ```
     */
    public Post<T extends IContent>(
        path: string,
        contentBody: T): Observable<SavedContent<T>> {
        (contentBody as T & {'__ContentType': string | undefined}).__ContentType = contentBody.Type;
        return this._repository
            .Ajax(ODataHelper.getContentURLbyPath(path), 'POST', ODataResponse, JSON.stringify(contentBody))
            .map((resp) => resp.d)
            .share();
    }
 
    /**
     * Method to delete a Content from the Content Repository through OData REST API.
     *
     * @param {number} id Id of the Content that will be deleted.
     * @param {number} permanentc Determines whether the Content should be moved to the Trash or be deleted permanently.
     * @returns {Observable} Returns an observable that you can subscribe of in your code.
     */
    public Delete = (id: number, permanent?: boolean): Observable<any> =>
        this._repository.Ajax(`/content(${id})`, 'DELETE', Object, { permanent }).share()
 
    /**
     * Method to modify a single or multiple fields of a Content through OData REST API.
     *
     * @param {number} id Id of the Content that will be modified.
     * @param {{new(...args): T}} contentType The type of the content
     * @param {Partial<T['options']>} fields Contains the modifiable fieldnames as keys and their values.
     * @returns {Observable} Returns an Rxjs observable that you can subscribe of in your code.
     *
     * ```ts
     * myODataApi.Patch(3, ContentTypes.Task, {
     *       Name: 'MyUpdatedTask'
     *  })
     * .subscribe(result=>{
     *      console.log('My Updated Task is:', result);
     * });
     * ```
     */
    public Patch<T extends IContent>(id: number, fields: T): Observable<T & ISavedContent> {
 
        const contentTypeWithResponse = ODataResponse as { new(...args: any[]): ODataResponse<T & ISavedContent> };
        return this._repository.Ajax(`/content(${id})`, 'PATCH', contentTypeWithResponse, `models=[${JSON.stringify(fields)}]`)
            .map((result) => result.d);
    }
 
    /**
     * Method to set multiple fields of a Content and clear the rest through OData REST API.
     *
     * This method creates an Observable, sends an ajax request to the server and convert the reponse to promise which will be the argument of the Observable.
     * @param {number} id Id of the Content that will be modified.
     * @param {{new(...args): T}} contentType The type of the content
     * @param {T['options']} fields Contains the modifiable fieldnames as keys and their values.
     * @returns {Observable} Returns an Rxjs observable that you can subscribe of in your code.
     *
     * ```ts
     * myODataApi.Put(3, ContentTypes.Task, {
     *       Name: 'MyUpdatedTask'
     *  })
     * .subscribe(result=>{
     *      console.log('My Updated Task is:', result);
     * });
     * ```
     */
    public Put<T extends IContent>(id: number, fields: T): Observable<SavedContent<T>> {
        const contentTypeWithResponse = ODataResponse as { new(...args: any[]): ODataResponse<SavedContent<T>> };
        return this._repository.Ajax(`/content(${id})`, 'PUT', contentTypeWithResponse, `models=[${JSON.stringify(fields)}]`)
            .map((result) => result.d);
    }
 
    /**
     * Creates a wrapper function for a callable custom OData action.
     *
     * This method creates an Observable, sends an ajax request to the server and convert the reponse to promise which will be the argument of the Observable.
     * @param {ICustomActionOptions} actionOptions A CustomAction configuration object.
     * @param {IODataParams} options An object that holds the config of the ajax request like urlparameters or data.
     * @param {new(...args): TReturnType} returns Th type that the action should return
     * @returns {Observable<TReturnType>} Returns an Rxjs observable whitch will be resolved with TReturnType that you can subscribe of in your code.
     */
    public CreateCustomAction<TReturnType>(actionOptions: ICustomActionOptions, options?: IODataParams<any>, returns?: { new(...args: any[]): TReturnType }): Observable<TReturnType> {
 
        const returnsType = returns || Object as { new(...args: any[]): any };
        const action = new CustomAction(actionOptions);
        const cacheParam = (action.noCache) ? '' : '&nocache=' + new Date().getTime();
        let path = '';
        if (typeof action.id !== 'undefined') {
            path = ODataHelper.joinPaths(ODataHelper.getContentUrlbyId(action.id), action.name);
        } else if (action.path) {
            path = ODataHelper.joinPaths(ODataHelper.getContentURLbyPath(action.path), action.name);
        } else {
            const error = new Error('No Id or Path provided.');
            this._repository.Events.Trigger.CustomActionFailed({
                ActionOptions: actionOptions,
                ODataParams: options,
                ResultType: returnsType,
                Error: error
            });
            throw error;
        }
        if (cacheParam.length > 0) {
            path = `${path}?${cacheParam}`;
        }
 
        if (path.indexOf('OData.svc(') > -1) {
            const start = path.indexOf('(');
            path = path.slice(0, start) + '/' + path.slice(start);
        }
 
        if (typeof action.isAction === 'undefined' || !action.isAction) {
            const ajax = this._repository.Ajax(path, 'GET', returnsType).share();
            ajax.subscribe((resp) => {
                this._repository.Events.Trigger.CustomActionExecuted({
                    ActionOptions: actionOptions,
                    ODataParams: options,
                    Result: resp
                });
            }, (err) => {
                this._repository.Events.Trigger.CustomActionFailed({
                    ActionOptions: actionOptions,
                    ODataParams: options,
                    ResultType: returnsType,
                    Error: err
                });
            });
            return ajax;
        } else {
            if (typeof options !== 'undefined' && typeof options.data !== 'undefined') {
                const ajax = this._repository.Ajax(path, 'POST', returnsType, JSON.stringify(options.data)).share();
                ajax.subscribe((resp) => {
                    this._repository.Events.Trigger.CustomActionExecuted({
                        ActionOptions: actionOptions,
                        ODataParams: options,
                        Result: resp
                    });
                }, (err) => {
                    this._repository.Events.Trigger.CustomActionFailed({
                        ActionOptions: actionOptions,
                        ODataParams: options,
                        ResultType: returnsType,
                        Error: err
                    });
                });
                return ajax;
            } else {
                const ajax = this._repository.Ajax(path, 'POST', returnsType).share();
                ajax.subscribe((resp) => {
                    this._repository.Events.Trigger.CustomActionExecuted({
                        ActionOptions: actionOptions,
                        ODataParams: options,
                        Result: resp
                    });
                }, (err) => {
                    this._repository.Events.Trigger.CustomActionFailed({
                        ActionOptions: actionOptions,
                        ODataParams: options,
                        ResultType: returnsType,
                        Error: err
                    });
                });
                return ajax;
            }
        }
    }
}