Press n or j to go to the next uncovered block, b, p or k for the previous block.
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 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 | 1x 1x 1x 1x 1x 1x 1x 24x 24x 24x 2x 1x 11x 11x 11x 22x 11x 11x 9x 9x 9x 1x 22x 22x 22x 22x 1x 21x 21x 21x 21x 7x 3x 3x 21x 11x 4x 3x 3x 1x 7x 1x 21x 21x 21x 21x 161x 124x 37x 37x 42x 10x 37x 33x 33x 23x 33x 42x 37x 15x 22x 22x 16x 21x 21x 1x 20x 1x 9x 9x 4x 2x 5x 5x 1x 7x 7x 7x 7x 1x 7x 7x 7x 14x 7x 7x 7x 7x 7x 7x 7x 1x 7x 1x 1x 1x 2x 1x 1x 1x 1x 3x 3x 6x 3x 3x 2x 1x 13x 13x 13x 13x 35x 35x 13x 22x 1x 2x 21x 1x 20x 22x 1x 10x 10x 10x 22x 22x 1x 1x 1x 1x 21x 1x 1x 20x 1x 47x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import {RestResourceError} from './error'; import {SessionInterface} from './auth/session/types'; import {RestClient} from './clients/rest'; import {RestRequestReturn} from './clients/rest/types'; import {DataType, GetRequestParams} from './clients/http_client/types'; import {ApiVersion} from './base-types'; import {Context} from './context'; export interface IdSet { [id: string]: string | number | null; } export interface ParamSet { [key: string]: any; } export interface Body { [key: string]: any; } export interface ResourcePath { http_method: string; operation: string; ids: string[]; path: string; } export interface BaseFindArgs { session: SessionInterface; params?: ParamSet; urlIds: IdSet; } export interface RequestArgs extends BaseFindArgs { http_method: string; operation: string; body?: Body | null; entity?: Base | null; } export interface BaseConstructorArgs { session: SessionInterface; fromData?: Body | null; } interface GetPathArgs { http_method: string; operation: string; urlIds: IdSet; entity?: Base | null; } E class Base { // For instance attributes [key: string]: any; public static API_VERSION: ApiVersion; public static NEXT_PAGE_INFO: GetRequestParams | undefined; public static PREV_PAGE_INFO: GetRequestParams | undefined; protected static NAME = ''; protected static PLURAL_NAME = ''; protected static PRIMARY_KEY = 'id'; protected static CUSTOM_PREFIX: string | null = null; protected static READ_ONLY_ATTRIBUTES: string[] = []; protected static HAS_ONE: {[attribute: string]: typeof Base} = {}; protected static HAS_MANY: {[attribute: string]: typeof Base} = {}; protected static PATHS: ResourcePath[] = []; protected static async baseFind({ session, urlIds, params, }: BaseFindArgs): Promise<Base[]> { const response = await this.request({ http_method: 'get', operation: 'get', session, urlIds, params, }); this.NEXT_PAGE_INFO = response.pageInfo?.nextPage ?? undefined; this.PREV_PAGE_INFO = response.pageInfo?.prevPage ?? undefined; return this.createInstancesFromResponse(session, response.body as Body); } protected static async request({ session, http_method, operation, urlIds, params, body, entity, }: RequestArgs): Promise<RestRequestReturn> { if (Context.API_VERSION !== this.API_VERSION) { throw new RestResourceError( `Current Context.API_VERSION '${Context.API_VERSION}' does not match resource version ${this.API_VERSION}`, ); } const client = new RestClient(session.shop, session.accessToken); const path = this.getPath({http_method, operation, urlIds, entity}); const cleanParams: {[key: string]: string | number} = {}; if (params) { for (const key in params) { if (params[key] !== null) { cleanParams[key] = params[key]; } } } switIch (http_method) { case 'get': return client.get({path, query: cleanParams}); case 'post': return client.post({ path, query: cleanParams, data: body!, type: DataType.JSON, }); case 'put': return client.put({ path, query: cleanParams, data: body!, type: DataType.JSON, }); caEse 'delete': return client.delete({path, query: cleanParams}); default: throw new Error(`Unrecognized HTTP method "${http_method}"`); } } protected static getJsonBodyName(): string { return this.name.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase(); }E private static getPath({ http_method, operation, urlIds, entity, }: GetPathArgs): string { let match: string | null = null; let specificity = -1; this.PATHS.forEach((path: ResourcePath) => { if ( http_method !== path.http_method || operation !== path.operation || path.ids.length <= specificity ) { return; } let pathUrlIds: IdSet = {...urlIds}; path.ids.forEach((id) => { if (!pathUrlIds[id] && entity && entity[id]) { pathUrlIds[id] = entity[id]; } }); pathUrlIds = Object.entries(pathUrlIds).reduce( (acc: IdSet, [key, value]: [string, string | number | null]) => { if (value) { acc[key] = value; } return acc; }, {}, ); // If we weren't given all of the path's required ids, we can't use it const diff = path.ids.reduce( (acc: string[], id: string) => (pathUrlIds[id] ? acc : acc.concat(id)), [], ); if (diff.length > 0) { return; } specificity = path.ids.length; match = path.path.replace( /(<([^>]+)>)/g, // eslint-disable-next-line @typescript-eslint/naming-convention (_m1, _m2, id) => `${pathUrlIds[id]}`, ); }); if (!match) { throw new RestResourceError('Could not find a path for request'); } if (this.CUSTOM_PREFIX) { return `${this.CUSTOM_PREFIX}/${match}`; } else { return match; } } private static createInstancesFromResponse( session: SessionInterface, data: Body, ): Base[] { if (data[this.PLURAL_NAME] || Array.isArray(data[this.NAME])) { return (data[this.PLURAL_NAME] || data[this.NAME]).reduce( (acc: Base[], entry: Body) => acc.concat(this.createInstance(session, entry)), [], ); } if (data[this.NAME]) { return [this.createInstance(session, data[this.NAME])]; } return []; } private static createInstance( session: SessionInterface, data: Body, prevInstance?: Base, ): Base { const instance: Base = prevInstance ? prevInstance : new (this as any)({session}); if (data) { instance.setData(data); } return instance; } public session: SessionInterface; constructor({session, fromData}: BaseConstructorArgs) { this.session = session; if (fromData) { this.setData(fromData); } } public async save({update = false} = {}): Promise<void> { const {PRIMARY_KEY, NAME} = this.resource(); const method = this[PRIMARY_KEY] ? 'put' : 'post'; const data = this.serialize(true); const response = await this.resource().request({ http_method: method, operation: method, session: this.session, urlIds: {}, body: {[this.resource().getJsonBodyName()]: data}, entity: this, }); const body: Body | undefined = (response.body as Body)[NAME]; if (update && body) { this.setData(body); } } public async saveAndUpdate(): Promise<void> { await this.save({update: true}); } public async delete(): Promise<void> { await this.resource().request({ http_method: 'delete', operation: 'delete', session: this.session, urlIds: {}, entity: this, }); } public serialize(saving = false): Body { const {HAS_MANY, HAS_ONE, READ_ONLY_ATTRIBUTES} = this.resource(); return Object.entries(this).reduce((acc: Body, [attribute, value]) => { if ( saving && (['session'].includes(attribute) || READ_ONLY_ATTRIBUTES.includes(attribute)) ) { return acc; } if (attribute in HAS_MANY && value) { acc[attribute] = value.reduce((attrAcc: Body, entry: Base) => { return attrAcc.concat(this.serializeSubAttribute(entry, saving)); }, []); } else if (attribute in HAS_ONE && value) { acc[attribute] = this.serializeSubAttribute(value, saving); } else { acc[attribute] = value; } return acc; }, {}); } protected setData(data: Body): void { const {HAS_MANY, HAS_ONE} = this.resource(); Object.entries(data).forEach(([attribute, val]) => { if (attribute in HAS_MANY) { const HasManyResource: typeof Base = HAS_MANY[attribute]; this[attribute] = []; val.forEach((entry: Body) => { this[attribute].push( new HasManyResource({session: this.session, fromData: entry}), ); }); } else if (attribute in HAS_ONE) { const HasOneResource: typeof Base = HAS_ONE[attribute]; this[attribute] = new HasOneResource({ session: this.session, fromData: val, }); } else { this[attribute] = val; } }); } private resource(): typeof Base { return this.constructor as unknown as typeof Base; } private serializeSubAttribute(attribute: Base, saving: boolean): Body { return attribute.serialize ? attribute.serialize(saving) : this.resource() .createInstance(this.session, attribute) .serialize(saving); } } export default Base; |