· 6 years ago · Nov 19, 2019, 08:24 AM
1import * as got from 'got';
2import { Interface } from 'readline';
3import { normalize } from 'path';
4var tough = require('tough-cookie');
5var Cookie = tough.Cookie;
6
7
8const obj = require('./test.json');
9const obj2 = require('./testupdate.json');
10
11
12const authData = {
13 secretKey: 'df4ddeeee4f1f095c8b40b023384adfeebd549f4',
14 login: 'space_boss@mail.ru',
15 apiUrl: 'https://spaceboss.amocrm.ru/private/api/auth.php'
16}
17interface authData {
18 secretKey: string;
19 login: string;
20 apiUrl: string;
21}
22interface ParamsAddTask {
23 element_type: number;
24 complete_till: DataCue;
25 task_type: number;
26 text: string;
27 responsible_user_id: number;
28 is_completed: boolean;
29 created_by: number;
30}
31interface ParamsUpdateTask {
32 id: number;
33 updated_at: DataCue;
34 text: string;
35}
36class CrmApi {
37 login: string;
38 hash: string;
39 url: string;
40 strForm: string;
41
42 addAndUpdateTaskUrl: string;
43 cookie: string;
44 constructor(login: string, hash: string, url: string) {
45 this.url = url;
46 this.strForm = JSON.stringify({
47 USER_LOGIN: login,
48 USER_HASH: hash
49 });
50 this.addAndUpdateTaskUrl = 'https://spaceboss.amocrm.ru/api/v2/tasks';
51 }
52
53 public async connect() {
54 let data: any = await got.post(this.url, {
55 body: this.strForm
56 }).catch(e => {
57 throw new Error(e)
58 })
59 this.getCookie(data)
60 }
61 public getCookie(data: any) {
62 this.cookie = Cookie.parse(data.headers['set-cookie'][0]);
63 console.log(this.cookie);
64 // this.cookie = ([data.headers['set-cookie'][0],data.headers['set-cookie'][1]]).join(',');
65 }
66
67 public errorCatcher() {
68
69 }
70 public async addTask(task: ParamsAddTask) {
71 let strTask = JSON.stringify(task);
72 await got.post(this.addAndUpdateTaskUrl, {
73 headers: {
74 'Content-Type': 'application/hal+json',
75 'Runtime-Timestamp': '1508320306',
76 cookie: this.cookie
77 },
78 body: strTask
79 }).then(() => {
80 console.log('Good')
81 }).catch(e => console.log(e));
82 }
83
84
85 public async updateTask(task: ParamsUpdateTask) {
86 let strTask = JSON.stringify(task);
87 await got.post(this.addAndUpdateTaskUrl, {
88 headers: {
89 'Content-Type': 'application/hal+json',
90 'Runtime-Timestamp': '1508320306',
91 cookie: this.cookie
92 },
93 body: strTask
94 }).then(() => {
95 console.log('Good')
96 }).catch(e => {
97 if (e.statusCode === 401) {
98 throw new Error('Unauthorized!')
99 }
100 throw new Error('idk error')
101 });
102 }
103}
104
105
106
107const api = new CrmApi(authData.login, authData.secretKey, authData.apiUrl);
108(async () => {
109 let a = await api.connect();
110 await api.addTask(obj);
111})();