New Types for JSForce (#24925)

Additional Types added for jsforce

analytics
metadata
chatter
This commit is contained in:
tnoonan-salesforce 2018-04-12 10:59:13 -06:00 committed by Mohamed Hegazy
parent df8f3b8b61
commit e77f5638ae
10 changed files with 693 additions and 16 deletions

82
types/jsforce/api/analytics.d.ts vendored Normal file
View File

@ -0,0 +1,82 @@
import { callback } from '../connection';
interface ReportInfo {
}
export class Dashboard {
describe(callback?: callback<object>): Promise<any>;
del(callback?: callback<object>): Promise<any>;
destory(callback?: callback<object>): Promise<any>;
delete(callback?: callback<object>): Promise<any>;
components(componentIds: () => any | string[] | string, callback?: callback<object>): Promise<any>;
status(callback?: callback<object>): Promise<any>;
refresh(callback?: callback<object>): Promise<any>;
clone(name: string | object, folderid: string, callback?: callback<object>): Promise<any>;
}
export class ReportInstance {
constructor(report: Report, id: string);
retrieve(callback: callback<ReportResult>): Promise<ReportResult>
}
export class Report {
describe(callback?: callback<ReportMetadata>): Promise<ReportMetadata>;
del(callback?: callback<ReportResult>): Promise<ReportResult>;
destory(callback?: callback<ReportResult>): Promise<ReportResult>;
delete(callback?: callback<ReportResult>): Promise<ReportResult>;
clone(name: string, callback?: callback<ReportResult>): Promise<ReportResult>;
explain(callback?: callback<ExplainInfo>): Promise<ExplainInfo>;
run(options: () => any | object, callback?: callback<ReportResult>): Promise<ReportResult>;
exec(options: () => any | object, callback?: callback<ReportResult>): Promise<ReportResult>;
execute(options: () => any | object, callback?: callback<ReportResult>): Promise<ReportResult>;
executeAsync(options: () => any | object, callback?: callback<ReportInstanceAttrs>): Promise<ReportInstanceAttrs>;
instance(id: string): ReportInstance;
instances(callback?: callback<ReportInstance[]>): Promise<ReportInstance[]>;
}
export interface ReportInstanceAttrs {
}
export interface ExplainInfo {
}
export interface ReportMetadata {
}
export interface ReportResult {
}
export interface ReportInfo {
}
export interface DashboardInfo {
}
export class Analytics {
report(id: string): Promise<Report>;
reports(callback?: callback<ReportInfo[]>): Promise<ReportInfo[]>;
dashboard(id: string): Promise<Dashboard>;
dashboards(callback?: callback<DashboardInfo[]>): Promise<DashboardInfo[]>;
}

71
types/jsforce/api/chatter.d.ts vendored Normal file
View File

@ -0,0 +1,71 @@
import { Connection, callback } from '../connection';
import { Query } from '../query';
import { Stream } from 'stream';
interface BatchRequestParams extends RequestParams {
method: string;
url: string;
richInput?: string;
}
interface BatchRequestResult {
statusCode: string;
result: RequestResult;
}
interface BatchRequestResults {
hasError: boolean;
results: BatchRequestResult[];
}
interface RequestParams {
method: string;
url: string;
body?: string;
}
export class RequestResult {
}
export class Request<T> implements Promise<T> {
constructor(chatter: Chatter, params: RequestParams);
batchParams(): BatchRequestParams;
promise(): Promise<T>;
stream(): Stream;
catch<TResult>(onrejected?: ((reason: any) => (PromiseLike<TResult> | TResult)) | null | undefined): Promise<T | TResult>;
then<TResult1, TResult2>(onfulfilled?: ((value: T) => (PromiseLike<TResult1> | TResult1)) | null | undefined,
onrejected?: ((reason: any) => (PromiseLike<TResult2> | TResult2)) | null | undefined): Promise<TResult1 | TResult2>;
thenCall(callback?: (err: Error, records: T) => void): Query<T>;
readonly [Symbol.toStringTag]: 'Promise';
}
export class Resource<T> extends Request<T> {
constructor(chatter: Chatter, url: string, queryParams?: object);
create(data: object | string, callback?: callback<T>): Request<T>;
del(callback?: callback<T>): Request<T>;
delete(callback?: callback<T>): Request<T>;
retrieve(callback?: callback<T>): Request<T>;
update(data: object, callback?: callback<T>): Request<T>;
}
export class Chatter {
constructor(conn: Connection);
batch(callback?: callback<BatchRequestResults>): Promise<BatchRequestResults>;
request(params: RequestParams, callback?: callback<Request<RequestResult>>): Request<RequestResult>;
resource(url: string, queryParams?: object): Resource<RequestResult>
}

178
types/jsforce/api/metadata.d.ts vendored Normal file
View File

@ -0,0 +1,178 @@
import { callback, Connection } from '../connection';
import { EventEmitter } from 'events';
import { Stream } from 'stream';
interface DeployResult {
id: string;
checkOnly: boolean;
completedDate: string;
createdDate: string;
details?: object[];
done: boolean;
errorMessage?: string;
errorStatusCode?: string;
ignoreWarnings?: boolean;
lastModifiedDate: string;
numberComponentErrors: number;
numberComponentsDeployed: number;
numberComponentsTotal: number;
numberTestErrors: number;
numberTestsCompleted: number;
numberTestsTotal: number;
rollbackOnError?: boolean;
startDate: string;
status: string;
success: boolean;
}
interface MetadataObject {
childXmlNames: string[];
directoryName: string;
inFolder: boolean;
metaFile: boolean;
suffix: string;
xmlName: string;
}
interface DescribeMetadataResult {
metadataObjects: MetadataObject[];
organizationNamespace: string;
partialSaveAllowed: boolean;
testRequired: boolean;
}
interface FileProperties {
type: string;
createdById: string;
createdByName: string;
createdDate: string;
fileName: string;
fullName: string;
id: string;
lastModifiedById: string;
lastModifiedByName: string;
lastModifiedDate: string;
manageableState?: string;
namespacePrefix?: string;
}
interface ListMetadataQuery {
type: string;
folder?: string;
}
interface MetadataInfo {
fullName: string;
}
interface RetrieveRequest {
}
interface RetrieveResult {
fileProperties: FileProperties[];
id: string;
messages: object[];
zipFile: string
}
interface SaveResult {
success: boolean;
fullName: string;
}
interface UpdateMetadataInfo {
currentName: string;
metadata: MetadataInfo;
}
interface UpsertResult {
success: boolean;
fullName: string;
created: boolean;
}
interface AsyncResult {
done: boolean;
id: string;
state: string;
statusCode?: string;
message?: string;
}
interface DeployOptions {
allowMissingFiles?: boolean;
autoUpdatePackage?: boolean;
checkOnly?: boolean;
ignoreWarnings?: boolean;
performRetrieve?: boolean;
purgeOnDelete?: boolean;
rollbackOnError?: boolean;
runAllTests?: boolean;
runTests?: string[];
singlePackage?: boolean;
}
export class AsyncResultLocator<T> extends EventEmitter implements Promise<T> {
check(callback?: callback<T>): Promise<T>
complete(callback?: callback<T>): Promise<T>
poll(interval: number, timeout: number): void;
catch<TResult>(onrejected?: ((reason: any) => (PromiseLike<TResult> | TResult)) | null | undefined): Promise<T | TResult>;
then<TResult1, TResult2>(onfulfilled?: ((value: T) => (PromiseLike<TResult1> | TResult1)) | null | undefined,
onrejected?: ((reason: any) => (PromiseLike<TResult2> | TResult2)) | null | undefined): Promise<TResult1 | TResult2>;
readonly [Symbol.toStringTag]: "Promise";
}
export class DeployResultLocator<T> extends AsyncResultLocator<T> {}
export class RetrieveResultLocator<T> extends AsyncResultLocator<T> {}
export class Metadata {
pollInterval: number;
pollTimeout: number;
constructor(conn: Connection);
checkDeployStatus(id: string, includeDetails?: boolean, callback?: callback<DeployResult>): Promise<DeployResult>
checkRetrieveStatus(id: string, callback?: callback<RetrieveResult>): Promise<RetrieveResult>
checkStatus(ids: string | string[], callback?: callback<AsyncResult | Array<AsyncResult>>): AsyncResultLocator<AsyncResult | Array<AsyncResult>>
create(type: string, metadata: MetadataInfo | Array<MetadataInfo>, callback?: callback<SaveResult | Array<SaveResult>>): Promise<SaveResult | Array<SaveResult>>
createAsync(type: string, metadata: MetadataInfo | Array<MetadataInfo>, callback?: callback<SaveResult | Array<SaveResult>>): Promise<SaveResult | Array<SaveResult>>
createSync(type: string, metadata: MetadataInfo | Array<MetadataInfo>, callback?: callback<SaveResult | Array<SaveResult>>): Promise<SaveResult | Array<SaveResult>>;
delete(type: string, fullNames: string | string[], callback?: callback<SaveResult | Array<SaveResult>>): Promise<SaveResult | Array<SaveResult>>;
deleteAsync(type: string, metadata: string | string[] | MetadataInfo | Array<MetadataInfo>, callback?: callback<AsyncResult | Array<AsyncResult>>): AsyncResultLocator<AsyncResult | Array<AsyncResult>>
deleteSync(type: string, fullNames: string | string[], callback?: callback<SaveResult | Array<SaveResult>>): Promise<SaveResult | Array<SaveResult>>;
deploy(zipInput: Stream | Buffer | string, options: DeployOptions, callback?:callback<AsyncResult>): DeployResultLocator<AsyncResult>;
describe(version?: string, callback?: callback<DescribeMetadataResult>): Promise<DescribeMetadataResult>;
list(queries: ListMetadataQuery | Array<ListMetadataQuery>, version?: string, callback?: callback<Array<FileProperties>>): Promise<Array<FileProperties>>;
read(type: string, fullNames: string | string[], callback?: callback<MetadataInfo | Array<MetadataInfo>>): Promise<MetadataInfo | Array<MetadataInfo>>;
readSync(type: string, fullNames: string | string[], callback?: callback<MetadataInfo | Array<MetadataInfo>>): Promise<MetadataInfo | Array<MetadataInfo>>;
rename(type: string, oldFullName: string, newFullName: string, callback?: callback<SaveResult>): Promise<SaveResult>
retrieve(request: RetrieveRequest, callback: callback<AsyncResult>): RetrieveResultLocator<AsyncResult>
update(type: string, updateMetadata: MetadataInfo | Array<MetadataInfo>, callback?: callback<SaveResult | Array<SaveResult>>): Promise<SaveResult | Array<SaveResult>>
updateAsync(type: string, updateMetadata: MetadataInfo, callback?: callback<AsyncResult | Array<AsyncResult>>): AsyncResultLocator<AsyncResult | Array<AsyncResult>>
updateSync(type: string, updateMetadata: MetadataInfo | Array<MetadataInfo>, callback?: callback<SaveResult | Array<SaveResult>>): Promise<SaveResult | Array<SaveResult>>
upsert(type: string, metadata: MetadataInfo | Array<MetadataInfo>, callback?: callback<UpsertResult | Array<UpsertResult>>): Promise<UpsertResult | Array<UpsertResult>>
}

View File

@ -1,8 +1,14 @@
import { SObjectCreateOptions } from './create-options';
import { DescribeSObjectResult } from './describe-result';
import { EventEmitter } from 'events';
import { DescribeSObjectResult, DescribeGlobalResult } from './describe-result';
import { Query, QueryResult } from './query';
import { Record } from './record';
import { RecordResult } from './record-result';
import { SObject } from './salesforce-object';
import { Analytics } from './api/analytics';
import { Chatter } from './api/chatter';
import { Metadata } from './api/metadata';
export type callback<T> = (err: Error, result: T) => void;
// These are pulled out because according to http://jsforce.github.io/jsforce/doc/connection.js.html#line49
// the oauth options can either be in the `oauth2` proeprty OR spread across the main connection
@ -13,6 +19,12 @@ export interface OAuth2Options {
redirectUri?: string;
}
export interface RequestInfo {
method?: string;
url?: string;
headers?: object;
}
export interface ConnectionOptions extends OAuth2Options {
accessToken?: string;
callOptions?: Object;
@ -36,6 +48,14 @@ export interface UserInfo {
url: string;
}
export abstract class RestApi {
get(path: string, options: object, callback: () => object): Promise<object>;
post(path: string, body: object, options: object, callback: () => object): Promise<object>;
put(path: string, body: object, options: object, callback: () => object): Promise<object>;
patch(path: string, body: object, options: object, callback: () => object): Promise<object>;
del(path: string, options: object, callback: () => object): Promise<object>;
}
export type ConnectionEvent = "refresh";
/**
@ -57,19 +77,58 @@ export type ConnectionEvent = "refresh";
*
* to ensure that you have the correct data types for the various collection names.
*/
export interface Connection {
export abstract class BaseConnection extends EventEmitter {
_baseUrl(): string;
request(info: RequestInfo | string, options?: Object, callback?: (err: Error, Object: object) => void): Promise<Object>;
query<T>(soql: string, callback?: (err: Error, result: QueryResult<T>) => void): Query<QueryResult<T>>;
queryMore<T>(locator: string, options?: object, callback?: (err: Error, result: QueryResult<T>) => void): Promise<QueryResult<T>>;
create<T>(type: string, records: Record<T>|Array<Record<T>>, options?: Object,
callback?: (err: Error, result: RecordResult | RecordResult[]) => void): Promise<(RecordResult | RecordResult[])>;
insert<T>(type: string, records: Record<T>|Array<Record<T>>, options?: Object,
callback?: (err: Error, result: RecordResult | RecordResult[]) => void): Promise<(RecordResult | RecordResult[])>;
retrieve<T>(type: string, ids: string|string[], options?: Object,
callback?: (err: Error, result: Record<T> | Array<Record<T>>) => void): Promise<(Record<T> | Array<Record<T>>)>;
update<T>(type: string, records: Record<T>|Array<Record<T>>, options?: Object,
callback?: (err: Error, result: RecordResult | Array<Record<T>>) => void): Promise<(RecordResult | RecordResult[])>;
upsert<T>(type: string, records: Record<T>|Array<Record<T>>, extIdField: string, options?: Object,
callback?: (err: Error, result: RecordResult | RecordResult[]) => void): Promise<(RecordResult | RecordResult[])>;
del<T>(type: string, ids: string|string[], options?: Object,
callback?: (err: Error, result: RecordResult | RecordResult[]) => void): Promise<(RecordResult | RecordResult[])>;
delete<T>(type: string, ids: string|string[], options?: Object,
callback?: (err: Error, result: RecordResult | RecordResult[]) => void): Promise<(RecordResult | RecordResult[])>;
destroy<T>(type: string, ids: string|string[], options?: Object,
callback?: (err: Error, result: RecordResult | RecordResult[]) => void): Promise<(RecordResult | RecordResult[])>;
describe<T>(type: string, callback?: (err: Error, result: DescribeSObjectResult) => void): Promise<DescribeSObjectResult>;
describeGlobal<T>(callback?: (err: Error, result: DescribeGlobalResult) => void): Promise<DescribeGlobalResult>;
sobject<T>(resource: string): SObject<T>;
}
export class Connection implements Connection {
export class Connection extends BaseConnection {
constructor(params: ConnectionOptions)
tooling: Tooling;
analytics: Analytics;
chatter: Chatter;
metadata: Metadata;
// Specific to Connection
instanceUrl: string;
version: string;
accessToken: string;
initialize(options?: ConnectionOptions): void;
queryAll<T>(soql: string, options?: object, callback?: (err: Error, result: QueryResult<T>) => void): Query<QueryResult<T>>;
authorize(code: string, callback?: (err: Error, res: UserInfo) => void): Promise<UserInfo>;
login(user: string, password: string, callback?: (err: Error, res: UserInfo) => void): Promise<UserInfo>;
loginByOAuth2(user: string, password: string, callback?: (err: Error, res: UserInfo) => void): Promise<UserInfo>;
loginBySoap(user: string, password: string, callback?: (err: Error, res: UserInfo) => void): Promise<UserInfo>;
logout(callback?: (err: Error, res: undefined) => void): Promise<void>;
logoutByOAuth2(callback?: (err: Error, res: undefined) => void): Promise<void>;
logoutBySoap(callback?: (err: Error, res: undefined) => void): Promise<void>;
on(eventName: ConnectionEvent, callback: Function): void;
}
export class Tooling extends BaseConnection {
_logger: any;
// Specific to tooling
executeAnonymous(body: string, callback?: (err: Error, res: any) => void): Promise<any>;
}

View File

@ -1,4 +1,30 @@
export interface DescribeSObjectResult {
label: string;
fields: string[];
fields: object[];
}
export interface DescribeGlobalResult {
activateable: boolean;
createable: boolean;
custom: boolean;
customSetting: boolean;
deletable: boolean;
deprecatedAndHidden: boolean;
feedEnabled: boolean;
hasSubtypes: boolean;
isSubtype: boolean;
keyPrefix: string;
label: string;
labelPlural: string;
layoutable: boolean;
mergeable: boolean;
mruEnabled: boolean;
name: string;
queryable: boolean;
replicateable: boolean;
retrieveable: boolean;
searchable: boolean;
triggerable: boolean;
undeletable: boolean;
updateable: boolean;
}

View File

@ -2,6 +2,8 @@
// Project: https://github.com/jsforce/jsforce
// Definitions by: Dolan Miu <https://github.com/dolanmiu>
// Kamil Ejsymont <https://github.com/netes>
// Thomas Dvornik <https://github.com/amphro>
// Tim Noonan <https://github.com/tnoonan-salesforce>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@ -13,6 +15,16 @@ import * as glob from 'glob';
export { Date } from './date-enum';
export { Record } from './record';
export { RecordResult } from './record-result';
export { Connection } from './connection';
export { Connection, ConnectionOptions, RequestInfo, Tooling, callback } from './connection';
export { SObject } from './salesforce-object';
export { SalesforceId } from './salesforce-id';
export { OAuth2, OAuth2Options } from './oauth2';
export { Query, QueryResult } from './query';
export { Promise } from './promise';
export { Report, Dashboard, Analytics, ReportInstance, DashboardInfo, ReportInfo, ExplainInfo, ReportInstanceAttrs,
ReportMetadata, ReportResult } from './api/analytics';
export { Chatter, Request, RequestResult, BatchRequestResults, BatchRequestParams,
Resource, BatchRequestResult, RequestParams } from './api/chatter';
export { Metadata, SaveResult, MetadataInfo, AsyncResult, RetrieveResultLocator, RetrieveRequest, FileProperties,
ListMetadataQuery, DescribeMetadataResult, DeployOptions, AsyncResultLocator, RetrieveResult, MetadataObject,
DeployResult, DeployResultLocator, UpdateMetadataInfo, UpsertResult } from './api/metadata';

View File

@ -79,7 +79,7 @@ salesforceConnection.query('SELECT Id FROM Account')
.on('end', (query: any) => {
console.log(records);
})
.on('error', (error) => {
.on('error', (error: Error) => {
console.log('Error returned from query:', error);
})
.run({ autoFetch: true, maxFetch: 25 });
@ -89,3 +89,191 @@ salesforceConnection.sobject<any>('Coverage__c')
salesforceConnection.sobject<any>('Coverage__c')
.select(['Id', 'Name']).del("test", () => { });
async function testAnalytics(conn: sf.Connection): Promise<void> {
const analytics: sf.Analytics = conn.analytics;
const dashboards: sf.DashboardInfo[] = await analytics.dashboards();
const dashboard = dashboards[0] as any;
Object.keys(dashboards[0])
.forEach((key: string) => console.log(`key: ${key} : ${dashboard[key]}`));
console.log('dashboard keys from await');
analytics.dashboards((err, dashboards: sf.DashboardInfo[]) => {
const _dashboard: any = dashboards[0] as any;
Object.keys(_dashboard)
.forEach((key: string) => console.log(`key: ${key} : ${_dashboard[key]}`));
console.log('dashboard keys from callback');
});
const reports: sf.ReportInfo[] = await analytics.reports();
const report: any = reports[0] as any;
Object.keys(reports[0]).forEach((key: string) => console.log(`key: ${key} : ${report[key]}`));
analytics.reports((err, reports: sf.ReportInfo[]) => {
const _report: any = reports[0] as any;
Object.keys(reports[0])
.forEach((key: string) => console.log(`key: ${key} : ${_report[key]}`));
console.log('report keys from callback');
});
}
async function testMetadata(conn: sf.Connection): Promise<void> {
const md: sf.Metadata = conn.metadata;
const m: sf.DescribeMetadataResult = await md.describe('34.0');
const pages: sf.MetadataObject[] =
m.metadataObjects.filter((value: sf.MetadataObject) => value.directoryName === 'pages');
console.log(`ApexPage?: ${pages[0].xmlName === 'ApexPage'}`);
const types: sf.ListMetadataQuery[] = [{type: 'CustomObject', folder: null}];
md.list(types, '39.0', (err, properties: sf.FileProperties[]) => {
if (err) {
console.error('err', err);
return;
}
const meta: sf.FileProperties = properties[0];
console.log('metadata count: ' + properties.length);
console.log('createdById: ' + meta.createdById);
console.log('createdByName: ' + meta.createdByName);
console.log('createdDate: ' + meta.createdDate);
console.log('fileName: ' + meta.fileName);
console.log('fullName: ' + meta.fullName);
console.log('id: ' + meta.id);
console.log('lastModifiedById: ' + meta.lastModifiedById);
console.log('lastModifiedByName: ' + meta.lastModifiedByName);
console.log('lastModifiedDate: ' + meta.lastModifiedDate);
console.log('manageableState: ' + meta.manageableState);
console.log('namespacePrefix: ' + meta.namespacePrefix);
console.log('type: ' + meta.type);
});
const fullNames: string[] = [ 'Account', 'Contact' ];
const info: sf.MetadataInfo | sf.MetadataInfo[] = await md.read('CustomObject', fullNames);
console.log((info as sf.MetadataInfo[])[0].fullName);
console.log((info as sf.MetadataInfo[])[1].fullName);
const now: number = Date.now();
const now2: number = now + 1;
const metadata = [{
fullName: `TestObject${now}__c`,
label: `Test Object ${now}`,
pluralLabel: `Test Object ${now}`,
nameField: {
type: 'Text',
label: `Test Object Name ${now}`
},
deploymentStatus: 'Deployed',
sharingModel: 'ReadWrite'
}, {
fullName: `TestObject${now2}__c`,
label: `Test Object ${now2}`,
pluralLabel: `Test Object ${now2}`,
nameField: {
type: 'AutoNumber',
label: 'Test Object #'
},
deploymentStatus: 'InDevelopment',
sharingModel: 'Private'
}];
const result: sf.SaveResult | sf.SaveResult[] = await md.create('CustomObject', metadata);
console.log(`created ${(result as sf.SaveResult[])[0].fullName} - ${(result as sf.SaveResult[])[0].success}`);
console.log(`created ${(result as sf.SaveResult[])[1].fullName} - ${(result as sf.SaveResult[])[1].success}`);
const fullNames2: string[] = [`TestObject${now}__c`, `TestObject${now2}__c`];
const result2: sf.SaveResult | sf.SaveResult[] =
await (md.delete('CustomObject', fullNames2) as Promise<sf.SaveResult[]>);
console.log(`deleted ${result2[0].fullName} - ${result2[0].success}`);
console.log(`deleted ${result2[1].fullName} - ${result2[1].success}`);
}
async function testChatter(conn: sf.Connection): Promise<void> {
const chatter: sf.Chatter = conn.chatter;
chatter.resource('/feed-elements').create({
body: {
messageSegments: [{
type: 'Text',
text: 'This is new post'
}]
},
feedElementType : 'FeedItem',
subjectId: 'me'
}, (err: Error, result: any) => {
if (err) {
throw err;
}
const feedMessageUrl = `/feed-elements/${result.id}/capabilities/comments/items`;
chatter.resource(feedMessageUrl).create({
body: {
messageSegments: [{
type: 'Text',
text: 'This is new comment on the post'
}]
}
}, (err: Error, result: any) => {
if (err) {
throw err;
}
console.log("Id: " + result.id);
console.log("URL: " + result.url);
console.log("Body: " + result.body.messageSegments[0].text);
});
});
const resourceMe: sf.Resource<sf.RequestResult> = chatter.resource('/users/me');
resourceMe.retrieve((err, res: any) => {
if (err) {
console.error(err);
return;
}
console.log("username: " + res.username);
console.log("email: " + res.email);
console.log("small photo url: " + res.photo.smallPhotoUrl);
});
chatter.resource('/users', { q: 'Suzuki' }).retrieve((err, result: any) => {
if (err) {
console.error(err);
return;
}
console.log("current page URL: " + result['currentPageUrl']);
console.log("next page URL: " + result['nextPageUrl']);
console.log("users count: " + result['users'].length);
for (const user of result['users']) {
console.log('User ID: ' + user.id);
console.log('User URL: ' + user.url);
console.log('Username: ' + user.username);
}
});
const feedResource: sf.Resource<sf.RequestResult> = chatter.resource('/feed-elements');
const feedCreateRequest: any = await (feedResource.create({
body: {
messageSegments: [{
type: 'Text',
text: 'This is new comment on the post'
}]
},
feedElementType : 'FeedItem',
subjectId: 'me'
}) as Promise<sf.RequestResult>);
console.log(`feedCreateRequest.id: ${feedCreateRequest.id}`);
const itemLikesUrl = `/feed-elements/${feedCreateRequest.id}/capabilities/chatter-likes/items`;
const itemsLikeResource: sf.Resource<sf.RequestResult> = chatter.resource(itemLikesUrl);
const itemsLikeCreateResult: sf.RequestResult = await (itemsLikeResource.create('') as Promise<sf.RequestResult>);
console.log(`itemsLikeCreateResult['likedItem']: ${itemsLikeCreateResult as any ['likedItem']}`);
}
(async () => {
const query2: sf.QueryResult<object> =
await (salesforceConnection.query("SELECT Id, Name FROM User") as Promise<sf.QueryResult<object>>);
console.log("Query Promise: total in database: " + query2.totalSize);
console.log("Query Promise: total fetched : " + query2.records[0]);
await testAnalytics(salesforceConnection);
await testChatter(salesforceConnection);
await testMetadata(salesforceConnection);
})();

35
types/jsforce/oauth2.d.ts vendored Normal file
View File

@ -0,0 +1,35 @@
export interface OAuth2Options {
authzServiceUrl?: string;
tokenServiceUrl?: string;
clientId?: string;
clientSecret?: string;
httpProxy?: string;
loginUrl?: string;
proxyUrl?: string;
redirectUri?: string;
refreshToken?: string;
revokeServiceUrl?: string;
authCode?: string;
privateKeyFile?: string;
privateKey?: string; // Used for sfdx auth files for legacy support reasons
}
export class OAuth2 {
constructor (options? : OAuth2Options);
protected _postParams(options: any, callback: () => any): void
loginUrl: string;
authzServiceUrl: string;
tokenServiceUrl: string;
revokeServiceUrl: string;
clientId: string;
clientSecret: string;
redirectUri: string;
getAuthorizationUrl(params: any): string;
refreshToken(code: string, callback?: () => any): Promise<any>;
requestToken(code: string, callback?: () => any): Promise<any>;
authenticate(username: string, password: string, callback?: () => any): Promise<any>;
revokeToken(accessToken: string, callback?: () => any): Promise<any>;
}

3
types/jsforce/promise.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
export class Promise {
thenCall: (cb: () => void) => void;
}

View File

@ -1,7 +1,5 @@
// http://jsforce.github.io/jsforce/doc/Query.html
import { Readable } from 'stream';
import { SalesforceId } from './salesforce-id';
import { RecordResult } from './record-result';
export interface ExecuteOptions {
@ -19,38 +17,63 @@ export interface QueryResult<T> {
export class Query<T> extends Readable implements Promise<T> {
end(): Query<T>;
filter(filter: Object): Query<T>;
include(include: string): Query<T>;
hint(hint: Object): Query<T>;
limit(value: number): Query<T>;
maxFetch(value: number): Query<T>;
offset(value: number): Query<T>;
skip(value: number): Query<T>;
sort(keyOrList: string | Object[] | Object, direction?: "ASC" | "DESC" | number): Query<T>;
sort(keyOrList: string | Object[] | Object, direction?: 'ASC' | 'DESC' | number): Query<T>;
run(options?: ExecuteOptions, callback?: (err: Error, records: T[]) => void): Query<T>;
execute(options?: ExecuteOptions, callback?: (err: Error, records: T[]) => void): Query<T>;
exec(options?: ExecuteOptions, callback?: (err: Error, records: T[]) => void): Query<T>;
del(type?: string, callback?: (err: Error, ret: RecordResult) => void): any;
del(callback?: (err: Error, ret: RecordResult) => void): any;
delete(type?: string, callback?: (err: Error, ret: RecordResult) => void): any;
delete(callback?: (err: Error, ret: RecordResult) => void): any;
destroy(type?: string, callback?: (err: Error, ret: RecordResult) => void): Promise<RecordResult[]>;
destroy(callback?: (err: Error, ret: RecordResult) => void): Promise<RecordResult[]>;
destroy(error?: Error): void;
explain(callback?: (err: Error, info: ExplainInfo) => void): Promise<ExplainInfo>;
map(callback: (currentValue: Object) => void): Promise<any>;
scanAll(value: boolean): Query<T>;
select(fields: Object | string[] | string): Query<T>;
thenCall(callback?: (err: Error, records: T) => void): Query<T>;
toSOQL(callback: (err: Error, soql: string) => void): Promise<string>;
update(mapping: any, type: string, callback: (err: Error, records: RecordResult[]) => void): Promise<RecordResult[]>;
where(conditions: Object | string): Query<T>;
// Implementing promise methods
then<T, never>(onfulfilled?: any): Promise<T | never>;
catch<never>(onrejected?: any): Promise<T>;
finally<never>(): Promise<T>;
[Symbol.toStringTag]: "Promise";
[Symbol.toStringTag]: 'Promise';
catch<TResult>(onrejected?: ((reason: any) => (PromiseLike<TResult> | TResult))): Promise<T | TResult>;
then<TResult1, TResult2>(onfulfilled?: ((value: T) => (PromiseLike<TResult1> | TResult1)),
onrejected?: ((reason: any) => (PromiseLike<TResult2> | TResult2))): Promise<TResult1 | TResult2>;
}
export class ExplainInfo { }
export class ExplainInfo {}