-
Notifications
You must be signed in to change notification settings - Fork 0
/
moltin.js
73 lines (60 loc) · 1.93 KB
/
moltin.js
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
"use strict";
const fs = require("fs");
const request = require("request-promise-native");
require("dotenv").load();
const MoltinGateway = require("@moltin/sdk").gateway;
const { createClient: MoltinClient } = require("@moltin/request");
const authenticate = async function(storage) {
const Moltin = MoltinGateway({
client_id: process.env.NEW_SITE_CLIENT_ID,
client_secret: process.env.NEW_SITE_SECRET
});
const expired =
!storage.get("mtoken") || Date.now().toString() >= storage.get("mexpires");
return expired ? await Moltin.Authenticate() : undefined;
};
const relate = function(id, type, resources) {
console.log("resiurces", resources);
return this.request.send(
`${this.endpoint}/${id}/relationships/${type}`,
"POST",
resources
);
};
const Moltin = MoltinGateway({
client_id: process.env.NEW_SITE_CLIENT_ID,
client_secret: process.env.NEW_SITE_SECRET
});
Moltin.Categories.CreateRelationships = relate;
Moltin.Products.CreateRelationshipsRaw = relate;
Moltin.Files = Object.setPrototypeOf(
Object.assign({}, Moltin.Products),
Moltin.Products
);
Moltin.Files.endpoint = "files";
Moltin.Files.Create = async function(file) {
const Moltin = MoltinGateway({
client_id: process.env.NEW_SITE_CLIENT_ID,
client_secret: process.env.NEW_SITE_SECRET
});
const { config, storage } = this.request;
await authenticate(storage);
const url = `${config.protocol}://${config.host}/${config.version}`;
const response = await request({
uri: `${url}/${this.endpoint}`,
method: "POST",
headers: {
Authorization: `Bearer: ${storage.get("mtoken")}`,
"Content-Type": "multipart/form-data",
"X-MOLTIN-SDK-LANGUAGE": config.sdk.language,
"X-MOLTIN-SDK-VERSION": config.sdk.version
},
formData: {
public: "true",
file_name: file.replace(/.+\//, ""),
file: fs.createReadStream(file)
}
});
return JSON.parse(response);
};
module.exports = Moltin;