-
Notifications
You must be signed in to change notification settings - Fork 18
/
playground.js
295 lines (272 loc) · 9.9 KB
/
playground.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
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
/* eslint-env node */
/* eslint-disable no-console */
// Don't show an error when devDependencies (i.e. colors) is imported
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
const colors = require('colors');
const repl = require('repl');
const commandLineArgs = require('command-line-args');
const commandLineUsage = require('command-line-usage');
const fs = require('fs');
const open = require('open');
const util = require('util');
const sharetribeSdk = require('./src/index');
const {LatLng, LatLgnBounds, UUID, Money, BigDecimal} = require('./src/types');
// Welcome message when Playground starts
const printWelcomeMessage = raw => {
colors.setTheme({
h1: 'yellow',
h2: 'yellow',
inline: 'gray',
block: 'gray',
});
if (raw) {
console.log('');
console.log(' # Playground (raw mode)'.h1);
console.log(' ');
console.log(' With the Marketplace API Playground you can test and try out the SDK with real results from the API.');
console.log(' ');
console.log(' ## Globals'.h2);
console.log(' ');
console.log(' The following globals are available:');
console.log(' ');
console.log(` - ${'`sharetribeSdk`'.inline}: The SDK module`);
console.log(` - ${'`printResponse`'.inline}: Helper function for pretty printing the API response.`);
console.log(` - ${'`pr`'.inline}: Helper function for pretty printing the API response from the last command that ran (presumably an API call).`);
console.log(` - ${'`apiDocs`'.inline}: Open the Marketplace API documentation in your browser.`);
console.log(' ');
console.log(' ## Example usage'.h2);
console.log(' ');
console.log(' Create new SDK instance:');
console.log(' ');
console.log(' ```'.block);
console.log(' const clientId = "<your clientId here>";'.block);
console.log(' const sdk = sharetribeSdk.createInstance({'.block);
console.log(' clientId,'.block);
console.log(' tokenStore: sharetribeSdk.tokenStore.memoryStore()'.block);
console.log(' });'.block);
console.log(' ```'.block);
console.log(' ');
console.log(' Print marketplace information:');
console.log(' ');
console.log(' sdk.marketplace.show().then(printResponse);'.block);
console.log(' ');
console.log(' Alternative version using pr():');
console.log(' ');
console.log(' sdk.marketplace.show();'.block);
console.log(' pr();'.block);
console.log(' ');
console.log(' Fetch 10 listings:');
console.log(' ');
console.log(' sdk.listings.query({per_page: 10}).then(response => {'.block);
console.log(' console.log("Fetched " + response.data.data.length + " listings.");'.block);
console.log(' response.data.data.forEach(listing => {'.block);
console.log(' console.log(listing.attributes.title);'.block);
console.log(' });'.block);
console.log(' });'.block);
console.log(' ');
console.log(` Type ${'`.exit`'.inline} when you want to exit the Playground`);
} else {
console.log('');
console.log(' # Playground'.h1);
console.log(' ');
console.log(' With the Marketplace API Playground you can test and try out the SDK with real results from the API.');
console.log(' ');
console.log(' ## Globals'.h2);
console.log(' ');
console.log(' The following globals are available:');
console.log(' ');
console.log(` - ${'`sharetribeSdk`'.inline}: The SDK module`);
console.log(` - ${'`sdk`'.inline}: An SDK instance initialized with your client ID`);
console.log(` - ${'`printResponse`'.inline}: Helper function for pretty printing the API response.`);
console.log(` - ${'`apiDocs`'.inline}: Open the Marketplace API documentation in your browser.`);
console.log(' ');
console.log(' ## Example usage'.h2);
console.log(' ');
console.log(' Print marketplace information:');
console.log(' ');
console.log(' sdk.marketplace.show().then(printResponse);'.block);
console.log(' ');
console.log(' Alternative version using pr():');
console.log(' ');
console.log(' sdk.marketplace.show();'.block);
console.log(' pr();'.block);
console.log(' ');
console.log(' Fetch 10 listings:');
console.log(' ');
console.log(' ```'.block);
console.log(' sdk.listings.query({per_page: 10}).then(response => {'.block);
console.log(' console.log("Fetched " + response.data.data.length + " listings.");'.block);
console.log(' response.data.data.forEach(listing => {'.block);
console.log(' console.log(listing.attributes.title);'.block);
console.log(' });'.block);
console.log(' });'.block);
console.log(' ```'.block);
console.log(' ');
console.log(` Type ${'`.exit`'.inline} when you want to exit the Playground`);
}
};
// CLI Usage information
const optionDefinitions = [
{
name: 'help',
description: 'Display this usage guide.',
alias: 'h',
type: Boolean
},
{
name: 'clientid',
description: 'Your Marketplace API Client ID to initialize the SDK with. You create your Client ID in Console: {underline https://console.sharetribe.com/advanced/applications}.',
alias: 'c',
typeLabel: '{underline ID}',
type: String
},
{
name: 'user',
description: 'The email of the user to log in with. The SDK is initialized in an authenticated state.',
alias: 'u',
typeLabel: '{underline email}',
type: String
},
{
name: 'password',
description: 'The password of the user to log in with. The SDK is initialized in an authenticated state.',
alias: 's',
typeLabel: '{underline password}',
type: String
},
{
name: 'raw',
description: 'Start the playground without initializing the SDK.',
type: Boolean
},
{
name: 'script',
description: 'Execute a playground script, i.e. a file that contains one or more playground commands.',
typeLabel: '{underline script_file.js}',
type: String
},
{
name: 'apidocs',
description: 'Open the Marketplace API reference using default browser.',
type: Boolean
}
];
const printUsage = () => {
console.log(commandLineUsage([
{
header: 'Marketplace API Playground',
content: 'The easiest way to call the Sharetribe Marketplace API using the JS SDK to try things out, to learn the APIs and to test your ideas.'
},
{
header: 'Options',
optionList: optionDefinitions
}
]));
};
const printResponse = response => {
console.log(JSON.stringify(response.data, null, 4));
return response;
}
const printLastResponse = (ctx) =>
() => ctx._.then(printResponse);
const apiDocs = () =>
open('https://www.sharetribe.com/api-reference/marketplace.html?javascript#marketplace-api')
.then(() => '');
const setupContext = (ctx, sdk) => {
ctx.sharetribeSdk = sharetribeSdk;
if (sdk) {
ctx.sdk = sdk;
}
ctx.printResponse = printResponse;
ctx.pr = printLastResponse(ctx);
ctx.apiDocs = apiDocs;
ctx.LatLng = LatLng;
ctx.LatLngBounds = LatLgnBounds;
ctx.UUID = UUID;
ctx.Money = Money;
ctx.BigDecimal = BigDecimal;
}
const startRepl = (sdk, rawMode, src) =>
() => {
if (src) {
// Setup context
setupContext(global, sdk);
// Start REPL
console.log('Executing script...');
console.log();
repl.start({
prompt: '> ',
input: src,
output: process.stdout,
useGlobal: true,
writer: result => result instanceof Promise ? '' : util.inspect(result)
});
} else {
printWelcomeMessage(rawMode);
// Start REPL
const replInstance = repl.start('> ');
// Attach history
// Node versions prior to 10.11 don't support setupHistory
if (replInstance.setupHistory) {
replInstance.setupHistory('./.repl_history', () => null);
}
// Setup context
const ctx = replInstance.context;
setupContext(ctx, sdk);
}
}
const exitOnFailure = msg =>
() => {
console.error(msg)
process.exit(1);
};
// Parse command line args
//
const options = commandLineArgs(optionDefinitions);
if (options.apidocs) {
apiDocs();
process.exit();
}
if (options.help || (!options.raw && options.clientid == null)) {
printUsage();
process.exit();
};
let scriptSrc;
if (options.script) {
scriptSrc = fs.createReadStream(options.script);
} else {
scriptSrc = null;
}
// If client ID is provided on start, instantiate and expose sdk
if (options.clientid) {
const sdk = sharetribeSdk.createInstance({
clientId: options.clientid,
tokenStore: sharetribeSdk.tokenStore.memoryStore()
});
// If user auth info is given too, log in with the user.
if (options.user && options.password) {
console.log(`Initializing SDK instance with Client ID: ${options.clientid}...`)
sdk.marketplace.show()
.then(result => console.log(`Successfully connected to ${result.data.data.attributes.name} marketplace.`))
.catch(exitOnFailure(`Unable to access the Marketplace API with the given Client ID: ${options.clientid}.`))
.then(() => {
console.log(`Logging in user ${options.user}...`);
return sdk.login({
username: options.user,
password: options.password
});
})
.catch(exitOnFailure(`Unable to log in with the email: ${options.user} and password you gave.`))
.then(startRepl(sdk, false, scriptSrc));
// No user auth, just Client ID
} else {
console.log(`Initializing SDK instance with Client ID: ${options.clientid}...`)
sdk.marketplace.show()
.then(result => console.log(`Successfully connected to ${result.data.data.attributes.name} marketplace.`))
.catch(exitOnFailure(`Unable to access the Marketplace API with the given Client ID: ${options.clientid}.`))
.then(startRepl(sdk, false, scriptSrc));
}
// Raw mode
} else {
startRepl(null, true, scriptSrc)();
}