Type definitions for APIs of WeChat Mini Program in TypeScript
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Complete cloud function, database, and storage APIs for WeChat Mini Program cloud development, providing serverless backend capabilities.
Invoke serverless cloud functions for backend processing.
interface WxCloud {
/** Initialize cloud environment */
init(options?: ICloud.InitOptions): void;
/** Call cloud function */
callFunction(options: ICloud.CallFunctionOptions): Promise<ICloud.CallFunctionResult>;
/** Call cloud container */
callContainer(options: ICloud.CallContainerOptions): Promise<ICloud.CallContainerResult>;
}
interface ICloud.CallFunctionOptions {
/** Cloud function name */
name: string;
/** Function parameters */
data?: Record<string, any>;
/** Slow query */
slow?: boolean;
/** Success callback */
success?(res: ICloud.CallFunctionResult): void;
/** Failure callback */
fail?(err: any): void;
/** Completion callback */
complete?(res: any): void;
}
interface ICloud.CallFunctionResult {
/** Function return value */
result: any;
/** Request ID */
requestID: string;
/** Error details */
errMsg: string;
}Usage Examples:
// Initialize cloud
wx.cloud.init({
env: 'my-env-id'
});
// Call cloud function
wx.cloud.callFunction({
name: 'getUserData',
data: {
userId: '12345'
}
}).then(res => {
console.log('Function result:', res.result);
}).catch(err => {
console.error('Function error:', err);
});
// Call with callback
wx.cloud.callFunction({
name: 'sendNotification',
data: {
message: 'Hello from client',
recipients: ['user1', 'user2']
},
success(res) {
console.log('Notification sent:', res.result);
}
});File upload, download, and management in cloud storage.
interface WxCloud {
/** Upload file to cloud storage */
uploadFile(options: ICloud.UploadFileOptions): Promise<ICloud.UploadFileResult>;
/** Download file from cloud storage */
downloadFile(options: ICloud.DownloadFileOptions): Promise<ICloud.DownloadFileResult>;
/** Get temporary file URL */
getTempFileURL(options: ICloud.GetTempFileURLOptions): Promise<ICloud.GetTempFileURLResult>;
/** Delete file from cloud storage */
deleteFile(options: ICloud.DeleteFileOptions): Promise<ICloud.DeleteFileResult>;
}
interface ICloud.UploadFileOptions {
/** Local file path */
cloudPath: string;
/** Cloud file path */
filePath: string;
/** File header */
header?: Record<string, string>;
/** Upload progress callback */
onUploadProgress?(progress: { loaded: number; total: number }): void;
/** Success callback */
success?(res: ICloud.UploadFileResult): void;
/** Failure callback */
fail?(err: any): void;
/** Completion callback */
complete?(res: any): void;
}
interface ICloud.UploadFileResult {
/** Cloud file ID */
fileID: string;
/** Status code */
statusCode: number;
/** Error message */
errMsg: string;
}Usage Examples:
// Upload file
wx.chooseImage({
count: 1,
success(chooseResult) {
const filePath = chooseResult.tempFilePaths[0];
const cloudPath = `images/${Date.now()}.jpg`;
wx.cloud.uploadFile({
cloudPath,
filePath,
onUploadProgress(progress) {
console.log('Upload progress:', progress.loaded / progress.total);
}
}).then(uploadResult => {
console.log('File uploaded:', uploadResult.fileID);
// Get download URL
return wx.cloud.getTempFileURL({
fileList: [uploadResult.fileID]
});
}).then(urlResult => {
console.log('Download URL:', urlResult.fileList[0].tempFileURL);
});
}
});
// Delete files
wx.cloud.deleteFile({
fileList: ['cloud://env-id.file-id-1', 'cloud://env-id.file-id-2']
}).then(res => {
console.log('Files deleted:', res.fileList);
});NoSQL database operations with MongoDB-like query interface.
interface WxCloud {
/** Get database reference */
database(options?: ICloud.DatabaseOptions): DB.Database;
}
interface DB.Database {
/** Get collection reference */
collection(name: string): DB.Collection;
/** Get current server timestamp */
serverDate(options?: { offset?: number }): DB.ServerDate;
/** Create regular expression query */
RegExp(options: { regexp: string; options?: string }): DB.RegExp;
/** Create geo point */
Geo: DB.Geo;
/** Database command helpers */
command: DB.Command;
}
interface DB.Collection {
/** Get document reference */
doc(id: string): DB.Document;
/** Add new document */
add(options: DB.AddOptions): Promise<DB.AddResult>;
/** Query documents */
get(options?: DB.GetOptions): Promise<DB.GetResult>;
/** Count documents */
count(): Promise<DB.CountResult>;
/** Update documents */
update(options: DB.UpdateOptions): Promise<DB.UpdateResult>;
/** Remove documents */
remove(): Promise<DB.RemoveResult>;
/** Set query conditions */
where(condition: DB.QueryCondition): DB.Query;
/** Order results */
orderBy(field: string, order: 'asc' | 'desc'): DB.Query;
/** Limit result count */
limit(value: number): DB.Query;
/** Skip results */
skip(value: number): DB.Query;
/** Select fields */
field(projection: Record<string, boolean>): DB.Query;
/** Watch for real-time updates */
watch(options?: DB.WatchOptions): DB.RealtimeListener;
/** Start aggregation pipeline */
aggregate(): DB.Aggregate;
}
interface DB.Document {
/** Get document data */
get(): Promise<DB.GetResult>;
/** Set document data */
set(options: DB.SetOptions): Promise<DB.SetResult>;
/** Update document */
update(options: DB.UpdateOptions): Promise<DB.UpdateResult>;
/** Remove document */
remove(): Promise<DB.RemoveResult>;
/** Watch document changes */
watch(options?: DB.WatchOptions): DB.RealtimeListener;
}Usage Examples:
const db = wx.cloud.database();
// Add document
db.collection('users').add({
data: {
name: 'John Doe',
age: 30,
email: 'john@example.com',
createdAt: db.serverDate()
}
}).then(res => {
console.log('User added:', res._id);
});
// Query documents
db.collection('users')
.where({
age: db.command.gte(18)
})
.orderBy('createdAt', 'desc')
.limit(10)
.get()
.then(res => {
console.log('Users found:', res.data);
});
// Update document
db.collection('users').doc('user-id').update({
data: {
lastLogin: db.serverDate(),
loginCount: db.command.inc(1)
}
});
// Real-time updates
const watcher = db.collection('messages')
.where({
chatId: 'chat-123'
})
.watch({
onChange(snapshot) {
console.log('Messages updated:', snapshot.docs);
},
onError(err) {
console.error('Watch error:', err);
}
});
// Stop watching
watcher.close();interface DB.Command {
/** Equal */
eq(value: any): DB.QueryCommand;
/** Not equal */
neq(value: any): DB.QueryCommand;
/** Greater than */
gt(value: any): DB.QueryCommand;
/** Greater than or equal */
gte(value: any): DB.QueryCommand;
/** Less than */
lt(value: any): DB.QueryCommand;
/** Less than or equal */
lte(value: any): DB.QueryCommand;
/** In array */
in(values: any[]): DB.QueryCommand;
/** Not in array */
nin(values: any[]): DB.QueryCommand;
/** And condition */
and(...conditions: DB.QueryCondition[]): DB.LogicCommand;
/** Or condition */
or(...conditions: DB.QueryCondition[]): DB.LogicCommand;
/** Increment */
inc(value: number): DB.UpdateCommand;
/** Set value */
set(value: any): DB.UpdateCommand;
/** Remove field */
remove(): DB.UpdateCommand;
/** Push to array */
push(...values: any[]): DB.UpdateCommand;
/** Pop from array */
pop(): DB.UpdateCommand;
/** Add to set */
addToSet(...values: any[]): DB.UpdateCommand;
/** Pull from array */
pull(condition: DB.QueryCondition): DB.UpdateCommand;
}interface DB.Aggregate {
/** Match documents */
match(condition: DB.QueryCondition): DB.Aggregate;
/** Project fields */
project(projection: Record<string, any>): DB.Aggregate;
/** Group documents */
group(group: Record<string, any>): DB.Aggregate;
/** Sort results */
sort(sort: Record<string, 1 | -1>): DB.Aggregate;
/** Limit results */
limit(value: number): DB.Aggregate;
/** Skip results */
skip(value: number): DB.Aggregate;
/** Lookup (join) */
lookup(lookup: {
from: string;
localField: string;
foreignField: string;
as: string;
}): DB.Aggregate;
/** Unwind array */
unwind(unwind: string | { path: string; preserveNullAndEmptyArrays?: boolean }): DB.Aggregate;
/** Execute aggregation */
end(): Promise<DB.AggregateResult>;
}Usage Examples:
// Complex query with operators
db.collection('products')
.where({
price: db.command.gte(100).and(db.command.lte(500)),
category: db.command.in(['electronics', 'books']),
inStock: true
})
.get();
// Aggregation pipeline
db.collection('orders')
.aggregate()
.match({
status: 'completed',
createdAt: db.command.gte(new Date('2023-01-01'))
})
.group({
_id: '$customerId',
totalAmount: db.command.aggregate.sum('$amount'),
orderCount: db.command.aggregate.sum(1)
})
.sort({
totalAmount: -1
})
.limit(10)
.end()
.then(res => {
console.log('Top customers:', res.list);
});interface DB.Geo {
/** Create geo point */
Point(longitude: number, latitude: number): DB.GeoPoint;
/** Create line string */
LineString(points: [number, number][]): DB.GeoLineString;
/** Create polygon */
Polygon(lineStrings: [number, number][][]): DB.GeoPolygon;
/** Create multi point */
MultiPoint(points: [number, number][]): DB.GeoMultiPoint;
/** Create multi line string */
MultiLineString(lineStrings: [number, number][][]): DB.GeoMultiLineString;
/** Create multi polygon */
MultiPolygon(polygons: [number, number][][][]): DB.GeoMultiPolygon;
}
interface DB.GeoQueryCommand {
/** Near query */
near(options: {
geometry: DB.GeoPoint;
maxDistance?: number;
minDistance?: number;
}): DB.QueryCommand;
/** Within query */
geoWithin(options: {
geometry: DB.GeoPolygon | DB.GeoMultiPolygon;
}): DB.QueryCommand;
/** Intersects query */
geoIntersects(options: {
geometry: any;
}): DB.QueryCommand;
}interface WxCloud {
/** Get AI model */
getModel(options: ICloud.GetModelOptions): Promise<ICloud.GetModelResult>;
/** Generate text */
generateText(options: ICloud.GenerateTextOptions): Promise<ICloud.GenerateTextResult>;
/** Create bot */
createBot(options: ICloud.CreateBotOptions): Promise<ICloud.CreateBotResult>;
/** Get bot */
getBot(options: ICloud.GetBotOptions): Promise<ICloud.GetBotResult>;
/** Send bot message */
sendBotMessage(options: ICloud.SendBotMessageOptions): Promise<ICloud.SendBotMessageResult>;
}
interface ICloud.GenerateTextOptions {
/** Model ID */
modelId: string;
/** Prompt */
prompt: string;
/** Generation parameters */
parameters?: {
maxTokens?: number;
temperature?: number;
topP?: number;
};
}// Cloud namespace
declare const wx: {
cloud: WxCloud;
};
// Database types
namespace DB {
interface QueryCondition {
[key: string]: any;
}
interface AddOptions {
data: Record<string, any>;
}
interface AddResult {
_id: string;
errMsg: string;
}
interface GetResult {
data: Record<string, any>[];
errMsg: string;
}
interface UpdateResult {
stats: {
updated: number;
};
errMsg: string;
}
interface RemoveResult {
stats: {
removed: number;
};
errMsg: string;
}
}
// Cloud function types
namespace ICloud {
interface InitOptions {
env?: string | { database?: string; functions?: string; storage?: string };
traceUser?: boolean;
}
}