import * as fs from 'fs-extra-promise' import * as dot from 'dot-prop' import * as Promise from 'bluebird' import { template } from '@cobalt-engine/utils' import { CoError } from '../../modules/co-error' import { ComponentLibraryRoutes, PublishOptions, ComponentDetail, NPMComponentData, ComponentCategory } from './interfaces' import { routes as routes} from './routes' export class ComponentLibraryClient { private routes: ComponentLibraryRoutes private url: string private request: any constructor(url: string, request: any){ this.routes = routes this.url = url this.request = request } publish (zipPath: string): Promise { var publishUrl = this.url + routes.publish var formData: PublishOptions = { package: fs.createReadStream(zipPath) } return this.request.post(publishUrl, { formData }) .get('data') .catch((err: CoError) => this.handleError(err)) } getCategoryList (): Promise { return this.request.get(this.url + routes.category) .get('data') .catch((err: CoError) => this.handleError(err)) } getAllVersions (componentName: string): Promise { var componentVersionsUrl = template(this.url + routes.versions, { name: componentName }) return this.request.get(componentVersionsUrl) .get('data') .catch((err: CoError) => this.handleError(err)) } getLatestVersion (componentName: string): Promise { var componentDataUrl = this.url + routes.install + '/' + componentName return this.getComponentLatestVersion(componentDataUrl) } getLatestVersionByCore (componentName: string, coreVersion: string): Promise { var componentDataUrl = template(this.url + routes.installByCore, { core: coreVersion }) + '/' + componentName return this.getComponentLatestVersion(componentDataUrl) } private getComponentLatestVersion (url: string): Promise { return this.request.get(url) .then(extractLatestVersion) .catch((err: CoError) => this.handleError(err)) } private handleError(err: CoError): never{ if(err.code === 'SERVER_ERROR' || err.code === 'SERVER_UNAVAILABLE'){ throw new CoError('COMPONENTS_LIBRARY_UNAVAILABLE', this.url) } throw err } } function extractLatestVersion (componentData: NPMComponentData): string { var latestVersionKeyPath = 'dist-tags.latest' return dot.get(componentData, latestVersionKeyPath) }