0
# Cloud Services
1
2
Complete cloud function, database, and storage APIs for WeChat Mini Program cloud development, providing serverless backend capabilities.
3
4
## Capabilities
5
6
### Cloud Function
7
8
Invoke serverless cloud functions for backend processing.
9
10
```typescript { .api }
11
interface WxCloud {
12
/** Initialize cloud environment */
13
init(options?: ICloud.InitOptions): void;
14
15
/** Call cloud function */
16
callFunction(options: ICloud.CallFunctionOptions): Promise<ICloud.CallFunctionResult>;
17
18
/** Call cloud container */
19
callContainer(options: ICloud.CallContainerOptions): Promise<ICloud.CallContainerResult>;
20
}
21
22
interface ICloud.CallFunctionOptions {
23
/** Cloud function name */
24
name: string;
25
/** Function parameters */
26
data?: Record<string, any>;
27
/** Slow query */
28
slow?: boolean;
29
/** Success callback */
30
success?(res: ICloud.CallFunctionResult): void;
31
/** Failure callback */
32
fail?(err: any): void;
33
/** Completion callback */
34
complete?(res: any): void;
35
}
36
37
interface ICloud.CallFunctionResult {
38
/** Function return value */
39
result: any;
40
/** Request ID */
41
requestID: string;
42
/** Error details */
43
errMsg: string;
44
}
45
```
46
47
**Usage Examples:**
48
49
```typescript
50
// Initialize cloud
51
wx.cloud.init({
52
env: 'my-env-id'
53
});
54
55
// Call cloud function
56
wx.cloud.callFunction({
57
name: 'getUserData',
58
data: {
59
userId: '12345'
60
}
61
}).then(res => {
62
console.log('Function result:', res.result);
63
}).catch(err => {
64
console.error('Function error:', err);
65
});
66
67
// Call with callback
68
wx.cloud.callFunction({
69
name: 'sendNotification',
70
data: {
71
message: 'Hello from client',
72
recipients: ['user1', 'user2']
73
},
74
success(res) {
75
console.log('Notification sent:', res.result);
76
}
77
});
78
```
79
80
### Cloud Storage
81
82
File upload, download, and management in cloud storage.
83
84
```typescript { .api }
85
interface WxCloud {
86
/** Upload file to cloud storage */
87
uploadFile(options: ICloud.UploadFileOptions): Promise<ICloud.UploadFileResult>;
88
89
/** Download file from cloud storage */
90
downloadFile(options: ICloud.DownloadFileOptions): Promise<ICloud.DownloadFileResult>;
91
92
/** Get temporary file URL */
93
getTempFileURL(options: ICloud.GetTempFileURLOptions): Promise<ICloud.GetTempFileURLResult>;
94
95
/** Delete file from cloud storage */
96
deleteFile(options: ICloud.DeleteFileOptions): Promise<ICloud.DeleteFileResult>;
97
}
98
99
interface ICloud.UploadFileOptions {
100
/** Local file path */
101
cloudPath: string;
102
/** Cloud file path */
103
filePath: string;
104
/** File header */
105
header?: Record<string, string>;
106
/** Upload progress callback */
107
onUploadProgress?(progress: { loaded: number; total: number }): void;
108
/** Success callback */
109
success?(res: ICloud.UploadFileResult): void;
110
/** Failure callback */
111
fail?(err: any): void;
112
/** Completion callback */
113
complete?(res: any): void;
114
}
115
116
interface ICloud.UploadFileResult {
117
/** Cloud file ID */
118
fileID: string;
119
/** Status code */
120
statusCode: number;
121
/** Error message */
122
errMsg: string;
123
}
124
```
125
126
**Usage Examples:**
127
128
```typescript
129
// Upload file
130
wx.chooseImage({
131
count: 1,
132
success(chooseResult) {
133
const filePath = chooseResult.tempFilePaths[0];
134
const cloudPath = `images/${Date.now()}.jpg`;
135
136
wx.cloud.uploadFile({
137
cloudPath,
138
filePath,
139
onUploadProgress(progress) {
140
console.log('Upload progress:', progress.loaded / progress.total);
141
}
142
}).then(uploadResult => {
143
console.log('File uploaded:', uploadResult.fileID);
144
145
// Get download URL
146
return wx.cloud.getTempFileURL({
147
fileList: [uploadResult.fileID]
148
});
149
}).then(urlResult => {
150
console.log('Download URL:', urlResult.fileList[0].tempFileURL);
151
});
152
}
153
});
154
155
// Delete files
156
wx.cloud.deleteFile({
157
fileList: ['cloud://env-id.file-id-1', 'cloud://env-id.file-id-2']
158
}).then(res => {
159
console.log('Files deleted:', res.fileList);
160
});
161
```
162
163
### Cloud Database
164
165
NoSQL database operations with MongoDB-like query interface.
166
167
```typescript { .api }
168
interface WxCloud {
169
/** Get database reference */
170
database(options?: ICloud.DatabaseOptions): DB.Database;
171
}
172
173
interface DB.Database {
174
/** Get collection reference */
175
collection(name: string): DB.Collection;
176
177
/** Get current server timestamp */
178
serverDate(options?: { offset?: number }): DB.ServerDate;
179
180
/** Create regular expression query */
181
RegExp(options: { regexp: string; options?: string }): DB.RegExp;
182
183
/** Create geo point */
184
Geo: DB.Geo;
185
186
/** Database command helpers */
187
command: DB.Command;
188
}
189
190
interface DB.Collection {
191
/** Get document reference */
192
doc(id: string): DB.Document;
193
194
/** Add new document */
195
add(options: DB.AddOptions): Promise<DB.AddResult>;
196
197
/** Query documents */
198
get(options?: DB.GetOptions): Promise<DB.GetResult>;
199
200
/** Count documents */
201
count(): Promise<DB.CountResult>;
202
203
/** Update documents */
204
update(options: DB.UpdateOptions): Promise<DB.UpdateResult>;
205
206
/** Remove documents */
207
remove(): Promise<DB.RemoveResult>;
208
209
/** Set query conditions */
210
where(condition: DB.QueryCondition): DB.Query;
211
212
/** Order results */
213
orderBy(field: string, order: 'asc' | 'desc'): DB.Query;
214
215
/** Limit result count */
216
limit(value: number): DB.Query;
217
218
/** Skip results */
219
skip(value: number): DB.Query;
220
221
/** Select fields */
222
field(projection: Record<string, boolean>): DB.Query;
223
224
/** Watch for real-time updates */
225
watch(options?: DB.WatchOptions): DB.RealtimeListener;
226
227
/** Start aggregation pipeline */
228
aggregate(): DB.Aggregate;
229
}
230
231
interface DB.Document {
232
/** Get document data */
233
get(): Promise<DB.GetResult>;
234
235
/** Set document data */
236
set(options: DB.SetOptions): Promise<DB.SetResult>;
237
238
/** Update document */
239
update(options: DB.UpdateOptions): Promise<DB.UpdateResult>;
240
241
/** Remove document */
242
remove(): Promise<DB.RemoveResult>;
243
244
/** Watch document changes */
245
watch(options?: DB.WatchOptions): DB.RealtimeListener;
246
}
247
```
248
249
**Usage Examples:**
250
251
```typescript
252
const db = wx.cloud.database();
253
254
// Add document
255
db.collection('users').add({
256
data: {
257
name: 'John Doe',
258
age: 30,
259
email: 'john@example.com',
260
createdAt: db.serverDate()
261
}
262
}).then(res => {
263
console.log('User added:', res._id);
264
});
265
266
// Query documents
267
db.collection('users')
268
.where({
269
age: db.command.gte(18)
270
})
271
.orderBy('createdAt', 'desc')
272
.limit(10)
273
.get()
274
.then(res => {
275
console.log('Users found:', res.data);
276
});
277
278
// Update document
279
db.collection('users').doc('user-id').update({
280
data: {
281
lastLogin: db.serverDate(),
282
loginCount: db.command.inc(1)
283
}
284
});
285
286
// Real-time updates
287
const watcher = db.collection('messages')
288
.where({
289
chatId: 'chat-123'
290
})
291
.watch({
292
onChange(snapshot) {
293
console.log('Messages updated:', snapshot.docs);
294
},
295
onError(err) {
296
console.error('Watch error:', err);
297
}
298
});
299
300
// Stop watching
301
watcher.close();
302
```
303
304
### Database Query Operators
305
306
```typescript { .api }
307
interface DB.Command {
308
/** Equal */
309
eq(value: any): DB.QueryCommand;
310
311
/** Not equal */
312
neq(value: any): DB.QueryCommand;
313
314
/** Greater than */
315
gt(value: any): DB.QueryCommand;
316
317
/** Greater than or equal */
318
gte(value: any): DB.QueryCommand;
319
320
/** Less than */
321
lt(value: any): DB.QueryCommand;
322
323
/** Less than or equal */
324
lte(value: any): DB.QueryCommand;
325
326
/** In array */
327
in(values: any[]): DB.QueryCommand;
328
329
/** Not in array */
330
nin(values: any[]): DB.QueryCommand;
331
332
/** And condition */
333
and(...conditions: DB.QueryCondition[]): DB.LogicCommand;
334
335
/** Or condition */
336
or(...conditions: DB.QueryCondition[]): DB.LogicCommand;
337
338
/** Increment */
339
inc(value: number): DB.UpdateCommand;
340
341
/** Set value */
342
set(value: any): DB.UpdateCommand;
343
344
/** Remove field */
345
remove(): DB.UpdateCommand;
346
347
/** Push to array */
348
push(...values: any[]): DB.UpdateCommand;
349
350
/** Pop from array */
351
pop(): DB.UpdateCommand;
352
353
/** Add to set */
354
addToSet(...values: any[]): DB.UpdateCommand;
355
356
/** Pull from array */
357
pull(condition: DB.QueryCondition): DB.UpdateCommand;
358
}
359
```
360
361
### Database Aggregation
362
363
```typescript { .api }
364
interface DB.Aggregate {
365
/** Match documents */
366
match(condition: DB.QueryCondition): DB.Aggregate;
367
368
/** Project fields */
369
project(projection: Record<string, any>): DB.Aggregate;
370
371
/** Group documents */
372
group(group: Record<string, any>): DB.Aggregate;
373
374
/** Sort results */
375
sort(sort: Record<string, 1 | -1>): DB.Aggregate;
376
377
/** Limit results */
378
limit(value: number): DB.Aggregate;
379
380
/** Skip results */
381
skip(value: number): DB.Aggregate;
382
383
/** Lookup (join) */
384
lookup(lookup: {
385
from: string;
386
localField: string;
387
foreignField: string;
388
as: string;
389
}): DB.Aggregate;
390
391
/** Unwind array */
392
unwind(unwind: string | { path: string; preserveNullAndEmptyArrays?: boolean }): DB.Aggregate;
393
394
/** Execute aggregation */
395
end(): Promise<DB.AggregateResult>;
396
}
397
```
398
399
**Usage Examples:**
400
401
```typescript
402
// Complex query with operators
403
db.collection('products')
404
.where({
405
price: db.command.gte(100).and(db.command.lte(500)),
406
category: db.command.in(['electronics', 'books']),
407
inStock: true
408
})
409
.get();
410
411
// Aggregation pipeline
412
db.collection('orders')
413
.aggregate()
414
.match({
415
status: 'completed',
416
createdAt: db.command.gte(new Date('2023-01-01'))
417
})
418
.group({
419
_id: '$customerId',
420
totalAmount: db.command.aggregate.sum('$amount'),
421
orderCount: db.command.aggregate.sum(1)
422
})
423
.sort({
424
totalAmount: -1
425
})
426
.limit(10)
427
.end()
428
.then(res => {
429
console.log('Top customers:', res.list);
430
});
431
```
432
433
### Geo Operations
434
435
```typescript { .api }
436
interface DB.Geo {
437
/** Create geo point */
438
Point(longitude: number, latitude: number): DB.GeoPoint;
439
440
/** Create line string */
441
LineString(points: [number, number][]): DB.GeoLineString;
442
443
/** Create polygon */
444
Polygon(lineStrings: [number, number][][]): DB.GeoPolygon;
445
446
/** Create multi point */
447
MultiPoint(points: [number, number][]): DB.GeoMultiPoint;
448
449
/** Create multi line string */
450
MultiLineString(lineStrings: [number, number][][]): DB.GeoMultiLineString;
451
452
/** Create multi polygon */
453
MultiPolygon(polygons: [number, number][][][]): DB.GeoMultiPolygon;
454
}
455
456
interface DB.GeoQueryCommand {
457
/** Near query */
458
near(options: {
459
geometry: DB.GeoPoint;
460
maxDistance?: number;
461
minDistance?: number;
462
}): DB.QueryCommand;
463
464
/** Within query */
465
geoWithin(options: {
466
geometry: DB.GeoPolygon | DB.GeoMultiPolygon;
467
}): DB.QueryCommand;
468
469
/** Intersects query */
470
geoIntersects(options: {
471
geometry: any;
472
}): DB.QueryCommand;
473
}
474
```
475
476
### AI Services
477
478
```typescript { .api }
479
interface WxCloud {
480
/** Get AI model */
481
getModel(options: ICloud.GetModelOptions): Promise<ICloud.GetModelResult>;
482
483
/** Generate text */
484
generateText(options: ICloud.GenerateTextOptions): Promise<ICloud.GenerateTextResult>;
485
486
/** Create bot */
487
createBot(options: ICloud.CreateBotOptions): Promise<ICloud.CreateBotResult>;
488
489
/** Get bot */
490
getBot(options: ICloud.GetBotOptions): Promise<ICloud.GetBotResult>;
491
492
/** Send bot message */
493
sendBotMessage(options: ICloud.SendBotMessageOptions): Promise<ICloud.SendBotMessageResult>;
494
}
495
496
interface ICloud.GenerateTextOptions {
497
/** Model ID */
498
modelId: string;
499
/** Prompt */
500
prompt: string;
501
/** Generation parameters */
502
parameters?: {
503
maxTokens?: number;
504
temperature?: number;
505
topP?: number;
506
};
507
}
508
```
509
510
## Types
511
512
```typescript { .api }
513
// Cloud namespace
514
declare const wx: {
515
cloud: WxCloud;
516
};
517
518
// Database types
519
namespace DB {
520
interface QueryCondition {
521
[key: string]: any;
522
}
523
524
interface AddOptions {
525
data: Record<string, any>;
526
}
527
528
interface AddResult {
529
_id: string;
530
errMsg: string;
531
}
532
533
interface GetResult {
534
data: Record<string, any>[];
535
errMsg: string;
536
}
537
538
interface UpdateResult {
539
stats: {
540
updated: number;
541
};
542
errMsg: string;
543
}
544
545
interface RemoveResult {
546
stats: {
547
removed: number;
548
};
549
errMsg: string;
550
}
551
}
552
553
// Cloud function types
554
namespace ICloud {
555
interface InitOptions {
556
env?: string | { database?: string; functions?: string; storage?: string };
557
traceUser?: boolean;
558
}
559
}
560
```