- 版本:1.21.2
- GitHub: https://github.com/NativeScript/nativescript-cloud
- NPM: https://npmjs.net.cn/package/nativescript-cloud
- 下载
- 昨天:0
- 上周:15
- 上个月:195
NativeScript Cloud
用于 NativeScript CLI 的云支持
内容
公共 API
本节描述了在安装了 nativescript-cloud
扩展并且需要 NativeScript CLI 作为库时可以调用的所有方法。您必须通过调用 loadExtensions 方法来加载已安装的扩展。之后,您将能够调用 nativescript-cloud
扩展中的方法
const tns = require("nativescript");
Promise.all(tns.extensibilityService.loadExtensions())
.then(loadedExtensionsData => {
// Write your code here, after all extensions are loaded.
});
注意:使用之前必须安装扩展。您可以通过调用 CLI 的 installExtension 方法来实现
tns.extensibilityService.installExtension("nativescript-cloud@latest")
.then(extensionData => console.log(`Successfully installed extension ${extensionData.extensionName}.`))
.catch(err => console.log("Failed to install extension."));
内容
- nsCloudBuildService
- nsCloudCodesignService
- nsCloudPublishService
- nsCloudApplicationService
- nsCloudAuthenticationService
- nsCloudUserService
- nsCloudAccountsService
- nsCloudEulaService
- nsCloudProjectService
- nsCloudKinveyService
- nsCloudConfigManager
nsCloudBuildService
nsCloudBuildService
允许在云中构建应用程序。您可以调用以下方法
build 方法
build
方法验证传递的参数,并尝试在云中构建应用程序。如果构建成功,则构建结果 (.apk, .aab, .ipa 或 .zip) 将被下载。结果包含有关整个构建过程的信息,下载构建结果的路径以及用于生成指向最新构建结果(在 S3 中)的 QR 码的信息
定义
/**
* Builds the specified application in the cloud and returns information about the whole build process.
* @param {INSCloudProjectSettings} projectSettings Describes the current project - project dir, application identifier, name and nativescript data, as well as additional options to control the build workflow.
* @param {string} platform The mobile platform for which the application should be built: Android or iOS.
* @param {string} buildConfiguration The build configuration - Debug or Release.
* @param {string} accountId the account which will be charged for the build.
* @param {IAndroidBuildData} androidBuildData Android specific information for the build.
* @param {IIOSBuildData} iOSBuildData iOS specific information for the build.
* @returns {Promise<IBuildResultData>} Information about the build process. It is returned only on successful build. In case the build fails, the Promise is rejected with the server information.
*/
build(projectSettings: INSCloudProjectSettings,
platform: string,
buildConfiguration: string,
accountId: string,
androidBuildData?: IAndroidBuildData,
iOSBuildData?: IIOSBuildData): Promise<IBuildResultData>;
每个参数的详细描述可以在此处找到 这里。
nsCloudBuildService 事件
nsCloudBuildService
触发以下事件
buildOutput
buildOutput
事件包含当前构建输出的部分
interface IBuildLog {
cloudOperationId: string;
data: string;
pipe: string;
}
stepChanged
stepChanged
事件包含已更改的构建步骤名称及其进度
/**
* Describes build step.
*/
interface IBuildStep {
/**
* The ID of the cloud operation.
*/
cloudOperationId: string;
/**
* The name of the step - prepare, upload, build or download.
*/
step: string;
/**
* The progress of the step in percents. The value will be between 0 and 100.
*/
progress: number;
}
事件使用
const tns = require("nativescript");
const fs = require("fs");
const path = require("path");
const packageJsonContent = JSON.parse(fs.readFileSync("./package.json", "utf8").toString());
const projectSettings = {
projectDir: process.cwd(),
projectId: packageJsonContent.nativescript.id,
projectName: path.dirname(process.cwd()),
nativeScriptData: packageJsonContent.nativescript,
bundle: true,
env: {
uglify: true
}
};
const androidReleaseConfigurationData = {
pathToCertificate: "./myCertificate.p12",
certificatePassword: "123456"
};
const platform = "android";
const buildConfiguration = "release";
tns.nsCloudBuildService.on("buildOutput", (data) => {
console.log(data);
/*
Sample data object:
{
"cloudOperationId": "2fb2e19c-3720-4fd1-9446-1df98f5e3531",
"pipe": "stdout",
"data": "Add platform ios with runtime version 2.5.*"
}
*/
});
tns.nsCloudBuildService.on("stepChanged", (data) => {
console.log(data);
/*
Sample data object:
{
"cloudOperationId": "2fb2e19c-3720-4fd1-9446-1df98f5e3531",
"step": "build";
"progress": 100;
}
*/
});
const accountId = "d0ce3ac0-36c2-427f-8d27-955915ffe189";
tns.nsCloudBuildService
.build(projectSettings, platform, buildConfiguration, accountId, androidReleaseConfigurationData)
.then(buildResult => console.log(buildResult))
.catch(err => console.error(err));
validateBuildProperties
validateBuildProperties
方法验证特定平台所需的所有属性。这包括检查当前应用程序标识符是否与 iOS 操作的 CodeSigning 身份匹配,检查指定的设备标识符(如果传递了)是否包含在移动配置文件中,验证密码等。
定义
/**
* Validates the build properties for specified platform (Android or iOS).
* The result promise is rejected with the error found. In case everything is correct, the promise is resolved.
* @param {string} platform The mobile platform for which the application should be built: Android or iOS.
* @param {string} buildConfiguration The build configuration - Debug or Release.
* @param {string} projectId Application identifier of the project.
* @param {IAndroidBuildData} androidBuildData Android speicific information for the build.
* @param {IIOSBuildData} iOSBuildData iOS speicific information for the build.
* @returns {Promise<void>}
*/
validateBuildProperties(platform: string,
buildConfiguration: string,
projectId: string,
androidBuildData?: IAndroidBuildData,
iOSBuildData?: IIOSBuildData): Promise<void>;
每个参数的详细描述可以在此处找到 这里。
使用方法
const tns = require("nativescript");
const fs = require("fs");
const path = require("path");
const packageJsonContent = JSON.parse(fs.readFileSync("./package.json", "utf8").toString());
const projectId = packageJsonContent.nativescript.id;
const androidReleaseConfigurationData = {
pathToCertificate: "./myCertificate.p12",
certificatePassword: "123456"
};
const platform = "android";
const buildConfiguration = "release";
tns.nsCloudBuildService
.validateBuildProperties(platform, buildConfiguration, projectId, androidReleaseConfigurationData)
.then(buildResult => console.log("Data is valid"))
.catch(err => console.error("Data is invalid:", err));
getBuildOutputDirectory
getBuildOutputDirectory
- 返回可以找到构建输出的目录路径。
此方法目前仅用于向后兼容。该模块现在实现了针对服务器操作的基本模块,以更通用的方法:
getServerOperationOutputDirectory
提供相同的功能。参数的详细描述可以在此处找到。
定义
/**
* Returns the path to the directory where the build output may be found.
* @param {ICloudBuildOutputDirectoryOptions} options Options that are used to determine the build output directory.
* @returns {string} The build output directory.
*/
getBuildOutputDirectory(options: ICloudBuildOutputDirectoryOptions): string;
参数的详细描述可以在此处找到。
使用方法
const tns = require("nativescript");
const cloudBuildOutputDirectory = tns.nsCloudBuildService
.getBuildOutputDirectory({
platform: "ios",
projectDir: "/tmp/myProject"
emulator: false
});
nsCloudCodesignService
nsCloudCodesignService
允许在云中生成签名文件(目前仅限iOS .p12和.mobileprovision)。您可以调用以下方法
generateCodesignFiles
generateCodesignFiles
方法验证传入的参数,并尝试在云中生成签名文件。如果成功,将下载结果文件(.p12和/或.mobileprovision)。结果包含有关错误(如果有)的信息以及下载的签名文件的路径(在S3中)。
定义
/**
* Generates codesign files in the cloud and returns s3 urls to certificate or/and provision.
* @param {ICodesignData} codesignData Apple speicific information.
* @param {string} projectDir The path of the project.
* @returns {Promise<ICodesignResultData>} Information about the generation process. It is returned only on successfull generation. In case there is some error, the Promise is rejected with the server information.
*/
generateCodesignFiles(codesignData: ICodesignData, projectDir: string): Promise<ICodesignResultData>;
参数的详细描述可以在此处找到。
使用方法
const tns = require("nativescript");
const codesignResultData = tns.nsCloudBuildService
.generateCodesignFiles({
username:'[email protected]',
password:'password',
platform: "ios",
clean: true,
attachedDevices: [{
displayName: 'iPhone',
identifier: 'cc3653b16f1beab6cf34a53af84c8a94cb2f0c9f'
}]
}, '/tmp/projects/myproj');
getServerOperationOutputDirectory
getServerOperationOutputDirectory
方法返回可能找到服务器请求输出文件的目录路径,如果有。在此实现中 - 生成的签名文件。
定义
/**
* Returns the path to the directory where the server request output may be found.
* @param {ICloudServerOutputDirectoryOptions} options Options that are used to determine the build output directory.
* @returns {string} The build output directory.
*/
getServerOperationOutputDirectory(options: ICloudServerOutputDirectoryOptions): string;
参数的详细描述可以在此处找到。
使用方法
const tns = require("nativescript");
const generateCodesignFilesOutputDirectory = tns.nsCloudBuildService
.getServerOperationOutputDirectory({
platform: "ios",
projectDir: "/tmp/myProject"
emulator: false
});
nsCloudPublishService
nsCloudPublishService
允许将构建包发布到应用商店(GooglePlay或iTunesConnect)。您可以调用以下方法
publishToItunesConnect
publishToItunesConnect
方法 - 将尝试将提供的包发布到iTunes Connect。
定义
/**
* Publishes the given .ipa packages to iTunes Connect.
* @param {IItunesConnectPublishData} publishData Data needed to publish to iTunes Connect.
* @returns {Promise<void>}
*/
publishToItunesConnect(publishData: IItunesConnectPublishData): Promise<void>;
参数的详细描述可以在此处找到。
使用方法
const tns = require("nativescript");
tns.nsCloudPublishService
.publishToItunesConnect({
credentials: {
username: "user",
password: "pass"
},
packagePaths: ["/tmp/myReleaseIpa.ipa"],
projectDir: "/tmp/myProject"
})
.then(() => {
console.log("Publishing succeeded");
})
.catch(err => console.error(err));
publishToGooglePlay
publishToGooglePlay
方法将尝试将提供的包发布到Google Play。
定义
/**
* Publishes the given .apk packages to Google Play.
* @param {IGooglePlayPublishData} publishData Data needed to publish to Google Play.
* @returns {Promise<void>}
*/
publishToGooglePlay(publishData: IGooglePlayPublishData): Promise<void>;
参数的详细描述可以在此处找到。
使用方法
const tns = require("nativescript");
tns.nsCloudPublishService
.publishToGooglePlay({
track: "alpha",
pathToAuthJson: "/tmp/myAuthJson.json",
packagePaths: ["/tmp/myReleaseApk.apk"],
projectDir: "/tmp/myProject"
})
.then(() => {
console.log("Publishing succeeded");
})
.catch(err => console.error(err));
nsCloudApplicationService
nsCloudApplicationService
允许对应用进行管理并收集有关应用当前状态的更多信息。您可以调用以下方法
shouldBuild
shouldBuild
方法将确定当前应用是否应该构建。
定义
/**
* Determines whether the application should be built or not.
* @param {IApplicationBuildConfig} config Settings used to help decide whether the project should be built or not.
* @returns {Promise<boolean>}
*/
shouldBuild(config: IApplicationBuildConfig): Promise<boolean>;
参数的详细描述可以在此处找到。
使用方法
const tns = require("nativescript");
tns.nsCloudApplicationService
.shouldBuild({
projectDir: "/tmp/myProject",
platform: "android",
outputPath: "/tmp/myProject/.cloud/android" // for cloud builds
})
.then((shouldBuild) => {
console.log("Should build? ", shouldBuild);
})
.catch(err => console.error(err));
shouldInstall
shouldInstall
方法将确定当前应用的包是否应该安装到指定的设备上。
定义
/**
* Determines whether the application's output package should be installed on the given device or not.
* @param {IApplicationInstallConfig} config Settings used to help decide whether the project's output should be installed or not.
* @returns {Promise<boolean>}
*/
shouldInstall(config: IApplicationInstallConfig): Promise<boolean>;
参数的详细描述可以在此处找到。
使用方法
const tns = require("nativescript");
tns.nsCloudPublishService
.shouldInstall({
projectDir: "/tmp/myProject",
deviceIdentifier: "192.168.56.101:5555",
outputPath: "/tmp/myProject/.cloud/ios" // for cloud builds
})
.then((shouldInstall) => {
console.log("Should install?", shouldInstall);
})
.catch(err => console.error(err));
nsCloudAuthenticationService
nsCloudAuthenticationService
用于与认证相关的操作(登录、注销等)。您可以调用以下方法
login
login
方法在本地服务器上启动,该服务器将返回登录响应。之后,如果存在options.openAction
,它将用于打开登录url。如果没有定义此选项,则将使用默认打开器。成功登录后返回用户信息。
定义
/**
* Opens login page and after successfull login saves the user information.
* If options.openAction is provided, it will be used to open the login url instead of the default opener.
* @param {ILoginOptions} options Optional settings for the login method.
* @returns {Promise<IUser>} Returns the user information after successful login.
*/
login(options?: ILoginOptions): Promise<IUser>;
每个参数的详细描述可以在此处找到。
使用方法
const tns = require("nativescript");
tns.nsCloudAuthenticationService
.login()
.then(userInfo => console.log(userInfo))
.catch(err => console.error(err));
const tns = require("nativescript");
const childProcess = require("child_process");
const openAction = url => {
const isWin = /^win/.test(process.platform);
const openCommand = isWin ? "start" : "open";
childProcess.execSync(`${openCommand} ${url}`);
};
const loginOptions = { openAction: openAction };
tns.nsCloudAuthenticationService
.login(loginOptions)
.then(userInfo => console.log(userInfo))
.catch(err => console.error(err));
logout
logout
方法使当前用户认证数据失效。
定义
/**
* Invalidates the current user authentication data.
* If options.openAction is provided, it will be used to open the logout url instead of the default opener.
* @param {IOpenActionOptions} options Optional settings for the logout method.
* @returns {void}
*/
logout(options?: IOpenActionOptions): void;
使用方法
const tns = require("nativescript");
tns.nsCloudAuthenticationService.logout();
const tns = require("nativescript");
const childProcess = require("child_process");
const openAction = url => {
const isWin = /^win/.test(process.platform);
const openCommand = isWin ? "start" : "open";
childProcess.execSync(`${openCommand} ${url}`);
};
const logoutOptions = { openAction: openAction };
tns.nsCloudAuthenticationService.logout(logoutOptions);
isUserLoggedIn
isUserLoggedIn
方法检查当前用户的访问令牌是否有效。如果是,该方法将返回true。如果不是,该方法将尝试颁发新的访问令牌。如果该方法无法颁发新令牌,它将返回false。
定义
/**
* CheChecks if there is user info and the access token of the current user is valid. The method will try to issue new access token if the current is not valid.
* @returns {Promise<boolean>} Returns true if the user is logged in.
*/
isUserLoggedIn(): Promise<boolean>;
使用方法
const tns = require("nativescript");
tns.nsCloudAuthenticationService
.isUserLoggedIn()
.then(isLoggedIn => console.log(isLoggedIn))
.catch(err => console.error(err));
refreshCurrentUserToken
refreshCurrentUserToken
方法使用当前用户的刷新令牌颁发新的访问令牌。
定义
/**
* Uses the refresh token of the current user to issue new access token.
*/
refreshCurrentUserToken(): Promise<void>;
使用方法
const tns = require("nativescript");
tns.nsCloudAuthenticationService.refreshCurrentUserToken()
.then(() => console.log("Success"))
.catch(err => console.error(err));
cancelLogin
cancelLogin
方法停止当前登录过程,并以错误拒绝登录承诺。
定义
/**
* Stops the current login process and rejects the login promise with an error.
* @returns {void}
*/
cancelLogin(): void;
使用方法
const tns = require("nativescript");
tns.nsCloudAuthenticationService
.login()
.then(userInfo => console.log(userInfo))
.catch(err => console.error(err));
tns.nsCloudAuthenticationService.cancelLogin();
接口
interface IUser {
email: string;
firstName: string;
lastName: string;
}
interface IAuthenticationService {
/**
* Uses username and password for login and after successfull login saves the user information.
* @param {string} username The username of the user.
* @param {string} password The password of the user.
* @returns {Promise<IUser>} Returns the user information after successful login.
*/
devLogin(username: string, password: string): Promise<IUser>;
/**
* Opens login page and after successfull login saves the user information.
* If options.openAction is provided, it will be used to open the login url instead of the default opener.
* @param {ILoginOptions} options Optional settings for the login method.
* @returns {Promise<IUser>} Returns the user information after successful login.
*/
login(options?: ILoginOptions): Promise<IUser>;
/**
* Invalidates the current user authentication data.
* If options.openAction is provided, it will be used to open the logout url instead of the default opener.
* @param {IOpenActionOptions} options Optional settings for the logout method.
* @returns {void}
*/
logout(options?: IOpenActionOptions): void;
/**
* Uses the refresh token of the current user to issue new access token.
*/
refreshCurrentUserToken(): Promise<void>;
/**
* Checks the token state of the current user.
* @returns {Promise<ITokenState>} Returns the token state
*/
getCurrentUserTokenState(): Promise<ITokenState>;
/**
* Stops the current login process and rejects the login promise with an error.
* @returns {void}
*/
cancelLogin(): void;
}
interface IOpenActionOptions {
/**
* Action which will receive url and decide how to open it.
*/
openAction?: (url: string) => void;
}
interface ILoginOptions extends IOpenActionOptions {
/**
* Sets the ammount of time which the login method will wait for login response in non-interactive terminal.
*/
timeout?: string;
}
interface ITokenState {
/**
* True if the access token is valid.
*/
isTokenValid: boolean;
/**
* The expiration timestamp. (1494.923982727)
*/
expirationTimestamp: number;
}
nsCloudUserService
nsCloudUserService
用于获取有关当前用户的信息或修改它。您可以调用以下方法
hasUser
hasUser
方法检查是否存在用户信息。
定义
/**
* Checks if there is user information.
* @returns {boolean} Returns true if there is user information.
*/
hasUser(): boolean;
使用方法
const tns = require("nativescript");
const hasUser = tns.nsCloudUserService.hasUser();
console.log(hasUser);
getUser
getUser
方法返回当前用户信息。
定义
/**
* Returns the current user information.
* @returns {IUser} The current user information.
*/
getUser(): IUser;
使用方法
const tns = require("nativescript");
const user = tns.nsCloudUserService.getUser();
console.log(user);
user
的示例结果将是
{
"email": "[email protected]",
"firstName": "First",
"lastName": "Last"
}
getUserData
getUserData
方法返回当前用户的信息和认证数据。
定义
/**
* Returns the user information and the authentication data for the current user.
* @returns {IUserData} The user information and the authentication data for the current user.
*/
getUserData(): IUserData;
使用方法
const tns = require("nativescript");
const userData = tns.nsCloudUserService.getUserData();
console.log(userData);
userData
的示例结果将是
{
"accessToken": "some token",
"refreshToken": "some refresh token",
"userInfo": {
"email": "[email protected]",
"firstName": "First",
"lastName": "Last"
}
}
setUserData
setUserData
方法设置当前用户的信息和认证数据。
定义
/**
* Sets the user information and the authentication data for the current user.
* @param {IUserdata} userData The user data to set.
* @returns {void}
*/
setUserData(userData: IUserData): void;
每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
const userData = {
accessToken: "some token",
refreshToken: "some refresh token",
userInfo: {
email: "[email protected]",
firstName: "First",
lastName: "Last"
}
};
tns.nsCloudUserService.setUserData(userData);
setToken
setToken
方法仅设置当前用户的令牌。
定义
/**
* Sets only the token of the current user.
* @param {ITokenData} token The token data.
* @returns void
*/
setToken(token: ITokenData): void;
每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
const token = {
accessToken: "some token"
};
tns.nsCloudUserService.setToken(token);
clearUserData
clearUserData
方法删除当前用户数据。
定义
/**
* Removes the current user data.
*/
clearUserData(): void;
使用方法
const tns = require("nativescript");
tns.nsCloudUserService.clearUserData();
getUserAvatar
getUserAvatar
方法返回可以下载头像图片的URL。
定义
/**
* Return the URL where the avatar picture can be downloaded from.
* @returns {Promise<string>} Return the URL where the avatar picture can be downloaded from. It will return null if the user does not have avatar or it is not logged in.
*/
getUserAvatar(): Promise<string>;
使用方法
const tns = require("nativescript");
tns.nsCloudUserService.getUserAvatar()
.then(userAvatar => console.log(userAvatar));
接口
interface IUserService {
/**
* Checks if there is user information.
* @returns {boolean} Returns true if there is user information.
*/
hasUser(): boolean;
/**
* Returns the current user information.
* @returns {IUser} The current user information.
*/
getUser(): IUser;
/**
* Returns the user information and the authentication data for the current user.
* @returns {IUserData} The user information and the authentication data for the current user.
*/
getUserData(): IUserData;
/**
* Sets the user information and the authentication data for the current user.
* @param {IUserdata} userData The user data to set.
* @returns {void}
*/
setUserData(userData: IUserData): void;
/**
* Sets only the token of the current user.
* @param {ITokenData} token The token data.
* @returns void
*/
setToken(token: ITokenData): void;
/**
* Removes the current user data.
*/
clearUserData(): void;
/**
* Return the URL where the avatar picture can be downloaded from.
* @returns {Promise<string>} Return the URL where the avatar picture can be downloaded from. It will return null if the user does not have avatar or it is not logged in.
*/
getUserAvatar(): Promise<string>;
}
nsCloudAccountsService
nsCloudAccountsService
提供了与账户交互的方法。您可以调用以下方法
getMyAccounts
getMyAccounts
方法返回当前用户可以使用的账户。每个用户都有自己的账户和共享账户。共享账户是指用户作为开发者被添加的账户。
定义
/**
* Returns all accounts which can be used from the current user.
* Each user can have personal account and shared accounts.
* @returns {Promise<IAccount[]>}
*/
getMyAccounts(): Promise<IAccount[]>
每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
tns.nsCloudAccountsService.getMyAccounts()
.then(accounts => console.log(accounts));
getUsageInfo
getUsageInfo
方法返回指定账户的使用信息。
定义
/**
* Returns the usage information for the provided account.
* @param {string} accountId Account id which will be used to get the usage info.
* @returns {Promise<IUsageInfo[]>}.
*/
getUsageInfo(accountId: string): Promise<IUsageInfo[]>;
每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
tns.nsCloudAccountsService.getUsageInfo("d0ce3ac0-36c2-427f-8d27-955915ffe189")
.then(usageInfo => console.log(usageInfo));
getAccountFeatures
getAccountFeatures
方法返回指定账户的所有订阅功能信息。
定义
/**
* Returns information about all subscription features of the provided account.
* @param accountIdOption Account id which will be parsed and used to find account.
*/
getAccountFeatures(accountIdOption: string): Promise<IDictionary<IFeatureInfo>>;
每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
tns.nsCloudAccountsService.getAccountFeatures("d0ce3ac0-36c2-427f-8d27-955915ffe189")
.then(featuresInfo => console.log(featuresInfo));
nsCloudEulaService
nsCloudEulaService
允许与EULA交互 - 检查当前EULA是否应该接受、接受它等。
getEulaData
getEulaData
方法提供当前EULA的信息 - 可以在哪里找到它以及用户是否应该接受它。当调用此方法时,如果当前进程尚未下载,它将下载最新的EULA。EULA必须在以下条件下接受
- 从未接受过。
- 以前接受过,但当前EULA不同,即用户之前未接受过。
在所有其他情况下(当前EULA与用户之前接受的相同,无法下载新EULA,但用户以前接受过EULA),该方法将返回EULA不应接受。
定义
/**
* Gives information about the EULA. This method downloads the EULA to a local file (once for process).
* @returns {Promise<IEulaData>} Information about the EULA - url and should the user accept it.
*/
getEulaData(): Promise<IEulaData>;
返回的结果类型如下
/**
* Contains information about EULA.
*/
interface IEulaData {
/**
* URL where the EULA can be found.
*/
url: string;
/**
* Defines if EULA should be accepted by user.
*/
shouldAcceptEula: boolean;
}
使用方法
const tns = require("nativescript");
tns.nsCloudEulaService.getEulaData()
.then(eulaData => console.log(`EULA url is: ${eulaData.url}. This EULA should ${eulaData.shouldAcceptEula ? "" : "not" } be accepted.`));
getEulaDataWitCache
getEulaDataWithCache
方法提供当前EULA的信息 - 可以在哪里找到它以及用户是否应该接受它。当调用此方法时,只有在过去24小时内尚未下载的情况下,它才会下载最新的EULA。这是此方法与getEulaData
的主要区别。EULA必须在以下条件下接受
- 从未接受过。
- 以前接受过,但当前EULA不同,即用户之前未接受过。
在所有其他情况下(当前EULA与用户之前接受的相同,无法下载新EULA,但用户以前接受过EULA),该方法将返回EULA不应接受。
定义
/**
* Gives information about the EULA. This method downloads the EULA to a local file (once for process)
* only in case the local copy has not been modified for more than 24 hours.
* @returns {Promise<IEulaData>} Information about the EULA - url and should the user accept it.
*/
getEulaDataWithCache(): Promise<IEulaData>;
返回的结果类型与getEulaData
返回的类型相同。
使用方法
const tns = require("nativescript");
tns.nsCloudEulaService.getEulaDataWithCache()
.then(eulaData => console.log(`EULA url is: ${eulaData.url}. This EULA should ${eulaData.shouldAcceptEula ? "" : "not" } be accepted.`));
acceptEula
acceptEula
方法下载最新的EULA(如果当前进程尚未下载),计算其shasum并将其保存到用户设置文件中。如果任何操作失败,acceptEula
Promise将被拒绝并带有错误。
定义
/**
* Accepts the EULA. The method first downloads the latest EULA (in case it has not been already downloaded in current process) and saves its shasum to user settings file.
* @returns {Promise<void>}
*/
acceptEula(): Promise<void>;
使用方法
const tns = require("nativescript");
tns.nsCloudEulaService.acceptEula()
.then(() => console.log(`Successfully accepted EULA.`))
.catch(err => console.error("Unable to accept EULA. Error is: ", err));
nsCloudProjectService
nsCloudProjectService
允许管理云项目。您可以调用以下方法
cleanupProject 方法
cleanupProject
方法清除所有用于优化的云构建数据。如果存在,该方法将清除所有AWS CodeCommit和构建机器工件。
定义
/**
* Cleans all AWS CodeCommit data and build machines artefacts if they exist.
* @param {ICleanupProjectDataBase} cleanupProjectData Data needed for project cleaning.
* @returns {Promise<ICleanupProjectResult>} Information about the cleanup. It includes AWS CodeCommit result and the result from the cleanup on each build machine.
* If the promise is rejected the error will contain cloudOperationId property.
*/
cleanupProject(cleanupProjectData: ICleanupProjectDataBase): Promise<ICleanupProjectResult>;
每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
tns.nsCloudProjectService.cleanupProject({ appIdentifier: "org.nativescript.test", projectName: "test" })
.then((result) => console.log(`Cleanup result: ${result}`))
.catch(err => console.error("Unable to clean cloud project. Error is: ", err));
nsCloudKinveyService
nsCloudKinveyService
允许与Kinvey mBaaS交互。您可以调用以下方法
getApps 方法
getApps
方法返回当前用户所有应用程序的信息。
定义
/**
* Returns information for all applications of the current user.
* @returns {Promise<IKinveyApplication[]>}
*/
getApps(): Promise<IKinveyApplication[]>;
每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
tns.nsCloudKinveyService.getApps()
.then(result => console.log(`Apps: ${result}`))
.catch(err => console.error("Unable to get apps. Error is: ", err));
createApp 方法
createApp
方法在当前用户的账户中创建应用程序。
定义
/**
* Creates application in the account of the current user.
* @param input Input required to create application.
* @returns {Promise<IKinveyApplication>}
*/
createApp(input: ICreateKinveyAppInput): Promise<IKinveyApplication>;
每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
const createAppInput = {
name: "ns-cloud"
};
tns.nsCloudKinveyService.createApp(createAppInput)
.then(result => console.log(`Created app: ${result}`))
.catch(err => console.error("Unable to create app. Error is: ", err));
createAuthService 方法
createAuthService
方法创建身份存储库。然后在此身份存储库中创建认证服务。然后它将提供的环境中的默认认证服务设置为新建的服务。然后它将提供的环境中的默认认证服务设置为新建的服务。目前支持的服务提供者是OAuth2、OIDC和SAML-Redirect。
定义
/**
* First this method creates identity store. Then it creates authentication service
* in this identity store. Then it sets the default authentication service in the provided environment
* to the newly created service.
* @param input Input required to create authentication service.
* @returns {Promise<IKinveyAuthService>}
*/
createAuthService(input: ICreateKinveyAuthService): Promise<IKinveyAuthService>;
每个参数的描述可以在这里找到。每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
// Create OAuth2 aithentication service.
const createOAuth2Options = {
name: "my-oauth2-service",
provider: {
type: "OAuth2",
remoteService: "https://test.com/oauth/token",
options: {
grantEndpoint: "https://test.com/authorize",
clientId: "<cleint-id>",
clientSecret: "<client-secret>",
userIdEndpoint: "https://test.com/userinfo",
scope: "<scope (e.g. openid)>"
}
}
};
const oauth2Input = {
appId: "<app-id>",
environmentId: "<env-id>",
redirectUri: ["https://auth.kinvey.com/oauth2/redirect", "http://example.com"],
authServiceOptions: createOAuth2Options
};
tns.nsCloudKinveyService.createAuthService(oauth2Input)
.then(result => console.log(`Created OAuth2 auth service: ${result}`))
.catch(err => console.error("Unable to create OAuth2 auth service. Error is: ", err));
// Create OIDC authentication service.
const createOIDCOptions = {
name: "my-oidc-service",
provider: {
type: "OIDC",
remoteService: "https://test.com/oauth/token",
options: {
grantEndpoint: "https://test.com/authorize",
clientId: "<client-id>",
clientSecret: "<client-secret>",
issuerId: "https://test.com",
scope: "<scope (e.g. profile)>"
}
}
};
const oidcInput = {
appId: "<app-id>",
environmentId: "<env-id>",
redirectUri: ["http://example.com"],
authServiceOptions: createOIDCOptions
};
tns.nsCloudKinveyService.createAuthService(oidcInput)
.then(result => console.log(`Created OIDC auth service: ${result}`))
.catch(err => console.error("Unable to create OIDC auth service. Error is: ", err));
// Create SAML-Redirect authentication service.
const createSAMLRedirectOptions = {
name: "my-auth-service",
provider: {
type: "SAML-Redirect",
remoteService: "https://test.com/samlp/<some-id>",
options: {
idpCertificate: "<certificate>"
}
}
};
const samlRedirectInput = {
appId: "<app-id>",
environmentId: "<env-id>",
redirectUri: ["http://example.com"],
authServiceOptions: createSAMLRedirectOptions
};
tns.nsCloudKinveyService.createAuthService(samlRedirectInput)
.then(result => console.log(`Created SAML-Redirect auth service: ${result}`))
.catch(err => console.error("Unable to create SAML-Redirect auth service. Error is: ", err));
updateAuthService 方法
updateAuthService
方法更新提供的认证服务。
定义
/**
* Updates the provided authentication service.
* @param input The id of the authentication service and full authentication service object.
* @returns {Promise<IKinveyAuthService>}
*/
updateAuthService(input: IUpdateKinveyAuthService): Promise<IKinveyAuthService>;
每个参数的描述可以在这里找到。每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
tns.nsCloudKinveyService.getDefaultAuthService({ environmentId: "<env-id>" })
.then(authService => {
const id = authService.id;
// The update auth service input can't contain the id parameter.
delete authService.id;
authService.name = "new-name";
const updateAuthServiceInput = {
authServiceId: id,
authService
};
return tns.nsCloudKinveyService.updateAuthService(updateAuthServiceInput);
})
.then(result => console.log(`Updated auth service: ${result}`))
.catch(err => console.error("Unable to update auth service. Error is: ", err));
getAuthServices 方法
getAuthServices
方法返回所有允许访问提供的环境的认证服务。
定义
/**
* Returns all authentication services which allow access to the provided environment.
* The result is grouped by the identity store id.
* @param input The environment id.
* @returns {Promise<IDictionary<IKinveyAuthService[]>>}
*/
getAuthServices(input: IGetKinveyAuthServices): Promise<IDictionary<IKinveyAuthService[]>>;
每个参数的描述可以在这里找到。每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
tns.nsCloudKinveyService.getAuthServices({ environmentId: "<env-id>" })
.then(result => console.log(`Auth services: ${result}`))
.catch(err => console.error("Unable to get auth services. Error is: ", err));
getDefaultAuthService 方法
getDefaultAuthService
方法返回提供的环境的默认认证服务。
定义
/**
* Returns the default authentication service for the provided environment.
* @param input The environment id.
* @returns {Promise<IKinveyAuthService>}
*/
getDefaultAuthService(input: IGetDefaultKinveyAuthService): Promise<IKinveyAuthService>;
每个参数的描述可以在这里找到。每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
tns.nsCloudKinveyService.getDefaultAuthService({ environmentId: "<env-id>" })
.then(result => console.log(`Default auth service: ${result}`))
.catch(err => console.error("Unable to get dafault auth service. Error is: ", err));
changeDefaultAuthService 方法
changeDefaultAuthService
方法更改提供的环境中的默认认证服务。
定义
/**
* Changes the default authentication service in the provided environment.
* @param input Input required to change the default authentication service.
* @returns {Promise<IKinveyAuthService>}
*/
changeDefaultAuthService(input: IChangeDefaultKinveyAuthService): Promise<IKinveyAuthService>;
每个参数的描述可以在这里找到。每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
tns.nsCloudKinveyService.getAuthServices({ environmentId: "<env-id>" })
.then(authServices => {
const identityStoreId = Object.keys(authServices)[0];
const authServiceId = authServices[identityStoreId][0].id;
const changeDefaultAuthServiceInput = {
environmentId: "<env-id>",
authServiceId,
identityStoreId
};
return tns.nsCloudKinveyService.changeDefaultAuthService(changeDefaultAuthServiceInput);
})
.then(result => console.log(`New default auth service: ${result}`))
.catch(err => console.error("Unable to change dafault auth service. Error is: ", err));
nsCloudConfigManager
nsCloudConfigManager
允许管理云配置。您可以调用以下方法
reset 方法
reset
将当前云配置重置为默认值 - 生产。
定义
/**
* Resets config.json to it's default values.
* @returns {void}
*/
reset(): void;
每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
tns.nsCloudConfigManager.reset();
applyConfig 方法
applyConfig
应用特定配置并将其保存到 config.json。
定义
/**
* Applies specific configuration and saves it in config.json
* @param {string} configName The name of the configuration to be applied.
* @param {IConfigOptions} [options] The config options.
* @param {IServerConfigBase} [globalServerConfig] The global server configuration which will
* be used when changing the configuration. This parameter will override the default global configuration.
* @returns {void}
*/
applyConfig(configName: string, options?: IConfigOptions, globalServerConfig?: IServerConfigBase): void;
每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
tns.nsCloudConfigManager.applyConfig("test");
getCurrentConfigData 方法
getCurrentConfigData
返回当前的云配置。
定义
/**
* Returns the current cloud configuration.
* @returns {IServerConfig}
*/
getCurrentConfigData(): IServerConfig;
每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
console.log(tns.nsCloudConfigManager.getCurrentConfigData());
getServiceDomainName 方法
getServiceDomainName
返回提供的云服务的域名。
定义
/**
* Returns the domain of the provided cloud service.
* @param serviceName The name of the cloud service.
* @returns {string}
*/
getServiceDomainName(serviceName: string): string;
每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
console.log(tns.nsCloudConfigManager.getServiceDomainName("accounts-service"));
getCloudServicesDomainNames 方法
getCloudServicesDomainNames
返回所有云服务的域名。
定义
/**
* Returns the domain names of all cloud services.
* @returns {string[]} The domain names of all cloud services.
*/
getCloudServicesDomainNames(): string[];
每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
console.log(tns.nsCloudConfigManager.getCloudServicesDomainNames());
getServiceValueOrDefault 方法
getServiceValueOrDefault
返回存储在提供的服务的配置中的值或存储在全局配置中的默认值。
定义
/**
* Returns the value stored in the configuration of the provided service or the default value stored in the
* global configuration.
* @param serviceName The name of the cloud service.
* @param valueName The name of the value.
* @returns {string} The value specified in the provided service config or the value specified in the global config.
*/
getServiceValueOrDefault(serviceName: string, valueName: string): string;
每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
console.log(tns.nsCloudConfigManager.getServiceValueOrDefault("accounts-service", "serverProto"));
printConfigData 方法
printConfigData
在进程的 stdout 上打印当前的云配置。
定义
/**
* Prints the current cloud configuration on the stdout of the process.
* @returns {void}
*/
printConfigData(): void;
每个参数的详细描述可以在这里找到。
使用方法
const tns = require("nativescript");
tns.nsCloudConfigManager.printConfigData();
开发
该项目是用 TypeScript 编写的。在克隆之后,您可以通过在终端中执行以下命令来设置它
$ npm i --ignore-scripts
- 备注:--ignore-scripts
是必须的。$ npm i -g grunt-cli
(仅在没有全局安装时使用)$ grunt test
(首次执行此命令可能需要一些时间,连续调用将工作得更快)
之后,您可以在代码中进行更改。要转换它们,只需执行
$ grunt
您可以通过执行以下命令打包库的新版本
$ grunt pack