UNPKG

johnny-cli

Version:

CLI for Johnny Deps

70 lines (58 loc) 1.81 kB
// @flow import fetch from 'node-fetch'; import settings from 'settings'; type TDll = {| name: string, packages: {[string]: string}, |}; const _missedTokenMessage = 'API token is missed'; // Init with either user credentials or access token export default (APIParams: {|token: string|} | {|password: string, username: string|}): { install: Function, requestToken: Function, start: Function, } => ({ install: async (params: TDll) => { if(!APIParams.token) throw _missedTokenMessage; try { await fetch(settings.API_ENDPOINTS.BUNDLE({name: params.name}), { body : JSON.stringify(params), headers: {'Auth': APIParams.token, 'Content-Type': 'application/json'}, method : 'PUT', }); } catch(error) { throw 'HTTP request failed'; } }, requestToken: async () => { if(!(APIParams.password && APIParams.username)) throw 'You must provide "username" and "password" in order to request a token'; let authorization = await fetch(settings.API_ENDPOINTS.TOKEN, { body : JSON.stringify({password: APIParams.password, username: APIParams.username}), headers: {'Content-Type': 'application/json'}, method : 'POST', }).then(response => response.json()); if(authorization.status === 400) throw 'Incorrect login or password'; return authorization.token; }, start: async (params: TDll) => { if(!APIParams.token) throw _missedTokenMessage; try { let response = await fetch(settings.API_ENDPOINTS.BUNDLES, { body : JSON.stringify(params), headers: {'Auth': APIParams.token, 'Content-Type': 'application/json'}, method : 'POST', }).then(response => response.json()); if(response.code === 11000) throw 'You already have dll with such name'; } catch(error) { throw 'HTTP request failed'; } }, });