Skip to content

Commit ea44ec0

Browse files
Allow for variable timeout #49
1 parent 2cddd67 commit ea44ec0

File tree

11 files changed

+63
-89
lines changed

11 files changed

+63
-89
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ import * as Https from 'nativescript-https'
6565
Https.request({
6666
url: 'https://httpbin.org/get',
6767
method: 'GET',
68+
timeout: 30 // seconds (default 10)
6869
}).then(function(response) {
6970
console.log('Https.request response', response)
7071
}).catch(function(error) {

demo/app/app.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
import * as application from 'tns-core-modules/application';
22

3-
application.start({moduleName: "main-page"});
3+
application.run({moduleName: "main-page"});

demo/app/main-page.ts

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1+
import * as Https from 'nativescript-https';
12
import * as Observable from 'tns-core-modules/data/observable';
2-
import * as Page from 'tns-core-modules/ui/page';
33
import * as fs from 'tns-core-modules/file-system';
44
import * as dialogs from 'tns-core-modules/ui/dialogs';
5-
import * as Https from 'nativescript-https';
5+
import * as Page from 'tns-core-modules/ui/page';
66

77
export function onNavigatingTo(args: Page.NavigatedData) {
88
let page = args.object as Page.Page;
@@ -14,6 +14,7 @@ function getRequest(url: string, allowLargeResponse = false) {
1414
{
1515
url,
1616
method: 'GET',
17+
timeout: 1,
1718
allowLargeResponse
1819
})
1920
.then(response => console.log('Https.request response', response))
@@ -57,22 +58,19 @@ export function enableSSLPinning(args: Observable.EventData) {
5758
let dir = fs.knownFolders.currentApp().getFolder('assets');
5859
let certificate = dir.getFile('httpbin.org.cer').path;
5960
Https.enableSSLPinning({host: 'httpbin.org', certificate});
60-
let context = (args.object as Page.View).bindingContext as Observable.Observable;
61-
context.set('enabled', true);
61+
console.log('enabled');
6262
}
6363

6464
export function enableSSLPinningExpired(args: Observable.EventData) {
6565
let dir = fs.knownFolders.currentApp().getFolder('assets');
6666
let certificate = dir.getFile('httpbin.org.expired.cer').path;
6767
Https.enableSSLPinning({host: 'httpbin.org', certificate});
68-
let context = (args.object as Page.View).bindingContext as Observable.Observable;
69-
context.set('enabled', true);
68+
console.log('enabled');
7069
}
7170

7271
export function disableSSLPinning(args: Observable.EventData) {
7372
Https.disableSSLPinning();
74-
let context = (args.object as Page.View).bindingContext as Observable.Observable;
75-
context.set('enabled', false);
73+
console.log('disabled');
7674
}
7775

7876

demo/nsconfig.json

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1 @@
1-
{
2-
"useLegacyWorkflow": false
3-
}
1+
{}

demo/package.json

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,29 +2,29 @@
22
"nativescript": {
33
"id": "org.nativescript.plugindemo.https",
44
"tns-android": {
5-
"version": "5.4.0"
5+
"version": "6.1.1"
66
},
77
"tns-ios": {
8-
"version": "5.4.0"
8+
"version": "6.1.1"
99
}
1010
},
1111
"dependencies": {
1212
"nativescript-https": "file:../src",
1313
"nativescript-theme-core": "^1.0.4",
14-
"nativescript-unit-test-runner": "^0.3.4",
15-
"tns-core-modules": "~5.4.0"
14+
"nativescript-unit-test-runner": "0.7.0",
15+
"tns-core-modules": "~6.1.1"
1616
},
1717
"devDependencies": {
1818
"jasmine-core": "^2.5.2",
19-
"karma": "^1.3.0",
20-
"karma-jasmine": "^1.0.2",
19+
"karma": "4.1.0",
20+
"karma-jasmine": "2.0.1",
2121
"karma-nativescript-launcher": "^0.4.0",
2222
"nativescript-css-loader": "~0.26.1",
23-
"nativescript-dev-typescript": "~0.7.4",
24-
"nativescript-dev-webpack": "0.24.1",
25-
"tns-platform-declarations": "~5.4.0",
23+
"nativescript-dev-webpack": "1.0.1",
24+
"tns-platform-declarations": "~6.1.1",
2625
"tslint": "~5.11.0",
27-
"typescript": "~2.9.0"
26+
"typescript": "3.4.5",
27+
"karma-webpack": "3.0.5"
2828
},
2929
"scripts": {
3030
"build.plugin": "cd ../src && npm run build",

demo/tsconfig.tns.json

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
2-
"extends": "./tsconfig",
3-
"compilerOptions": {
4-
"module": "es2015",
5-
"moduleResolution": "node"
6-
}
2+
"extends": "./tsconfig",
3+
"compilerOptions": {
4+
"module": "es2015",
5+
"moduleResolution": "node"
6+
}
77
}

demo/webpack.config.js

Lines changed: 20 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ module.exports = env => {
2828

2929
// Default destination inside platforms/<platform>/...
3030
const dist = resolve(projectRoot, nsWebpack.getAppPath(platform, projectRoot));
31-
const appResourcesPlatformDir = platform === "android" ? "Android" : "iOS";
3231

3332
const {
3433
// The 'appPath' and 'appResourcesPath' values are fetched from
@@ -39,12 +38,14 @@ module.exports = env => {
3938

4039
// You can provide the following flags when running 'tns run android|ios'
4140
snapshot, // --env.snapshot
41+
production, // --env.production
4242
uglify, // --env.uglify
4343
report, // --env.report
4444
sourceMap, // --env.sourceMap
4545
hiddenSourceMap, // --env.hiddenSourceMap
4646
hmr, // --env.hmr,
47-
unitTesting, // --env.unitTesting
47+
unitTesting, // --env.unitTesting,
48+
verbose, // --env.verbose
4849
} = env;
4950
const isAnySourceMapEnabled = !!sourceMap || !!hiddenSourceMap;
5051
const externals = nsWebpack.getConvertedExternals(env.externals);
@@ -58,14 +59,22 @@ module.exports = env => {
5859

5960
const tsConfigPath = resolve(projectRoot, "tsconfig.tns.json");
6061

61-
if (platform === "ios") {
62-
entries["tns_modules/tns-core-modules/inspector_modules"] = "inspector_modules.js";
62+
const areCoreModulesExternal = Array.isArray(env.externals) && env.externals.some(e => e.indexOf("tns-core-modules") > -1);
63+
if (platform === "ios" && !areCoreModulesExternal) {
64+
entries["tns_modules/tns-core-modules/inspector_modules"] = "inspector_modules";
6365
};
6466

6567
let sourceMapFilename = nsWebpack.getSourceMapFilename(hiddenSourceMap, __dirname, dist);
6668

69+
const itemsToClean = [`${dist}/**/*`];
70+
if (platform === "android") {
71+
itemsToClean.push(`${join(projectRoot, "platforms", "android", "app", "src", "main", "assets", "snapshots")}`);
72+
itemsToClean.push(`${join(projectRoot, "platforms", "android", "app", "build", "configurations", "nativescript-android-snapshot")}`);
73+
}
74+
75+
nsWebpack.processAppComponents(appComponents, platform);
6776
const config = {
68-
mode: uglify ? "production" : "development",
77+
mode: production ? "production" : "development",
6978
context: appFullPath,
7079
externals,
7180
watchOptions: {
@@ -170,24 +179,15 @@ module.exports = env => {
170179
unitTesting,
171180
appFullPath,
172181
projectRoot,
182+
ignoredFiles: nsWebpack.getUserDefinedEntries(entries, platform)
173183
}
174184
},
175185
].filter(loader => !!loader)
176186
},
177187

178188
{
179-
test: /-page\.ts$/,
180-
use: "nativescript-dev-webpack/script-hot-loader"
181-
},
182-
183-
{
184-
test: /\.(css|scss)$/,
185-
use: "nativescript-dev-webpack/style-hot-loader"
186-
},
187-
188-
{
189-
test: /\.(html|xml)$/,
190-
use: "nativescript-dev-webpack/markup-hot-loader"
189+
test: /\.(ts|css|scss|html|xml)$/,
190+
use: "nativescript-dev-webpack/hmr/hot-loader"
191191
},
192192

193193
{ test: /\.(html|xml)$/, use: "nativescript-dev-webpack/xml-namespace-loader" },
@@ -228,28 +228,18 @@ module.exports = env => {
228228
// Define useful constants like TNS_WEBPACK
229229
new webpack.DefinePlugin({
230230
"global.TNS_WEBPACK": "true",
231-
"process": undefined,
231+
"process": "global.process",
232232
}),
233233
// Remove all files from the out dir.
234-
new CleanWebpackPlugin([`${dist}/**/*`]),
234+
new CleanWebpackPlugin(itemsToClean, { verbose: !!verbose }),
235235
// Copy assets to out dir. Add your own globs as needed.
236236
new CopyWebpackPlugin([
237237
{ from: { glob: "fonts/**" } },
238238
{ from: { glob: "**/*.jpg" } },
239239
{ from: { glob: "**/*.png" } },
240240
{ from: { glob: "assets/*.cer" } },
241241
], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),
242-
// Generate a bundle starter script and activate it in package.json
243-
new nsWebpack.GenerateBundleStarterPlugin(
244-
// Don't include `runtime.js` when creating a snapshot. The plugin
245-
// configures the WebPack runtime to be generated inside the snapshot
246-
// module and no `runtime.js` module exist.
247-
(snapshot ? [] : ["./runtime"])
248-
.concat([
249-
"./vendor",
250-
"./bundle",
251-
])
252-
),
242+
new nsWebpack.GenerateNativeScriptEntryPointsPlugin("bundle"),
253243
// For instructions on how to set up workers with webpack
254244
// check out https://github.com/nativescript/worker-loader
255245
new NativeScriptWorkerPlugin(),
@@ -270,18 +260,6 @@ module.exports = env => {
270260
],
271261
};
272262

273-
// Copy the native app resources to the out dir
274-
// only if doing a full build (tns run/build) and not previewing (tns preview)
275-
if (!externals || externals.length === 0) {
276-
config.plugins.push(new CopyWebpackPlugin([
277-
{
278-
from: `${appResourcesFullPath}/${appResourcesPlatformDir}`,
279-
to: `${dist}/App_Resources/${appResourcesPlatformDir}`,
280-
context: projectRoot
281-
},
282-
]));
283-
}
284-
285263
if (report) {
286264
// Generate report files for bundles content
287265
config.plugins.push(new BundleAnalyzerPlugin({

src/https.android.ts

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ console.info('nativescript-https > Disabled SSL pinning by default');
6262

6363
let Client: okhttp3.OkHttpClient;
6464

65-
function getClient(reload: boolean = false): okhttp3.OkHttpClient {
65+
function getClient(reload: boolean = false, timeout: number = 10): okhttp3.OkHttpClient {
6666
// if (!Client) {
6767
// Client = new okhttp3.OkHttpClient()
6868
// }
@@ -139,6 +139,15 @@ function getClient(reload: boolean = false): okhttp3.OkHttpClient {
139139
console.warn('nativescript-https > Undefined host or certificate. SSL pinning NOT working!!!');
140140
}
141141
}
142+
143+
// set connection timeout to override okhttp3 default
144+
if (timeout) {
145+
client
146+
.connectTimeout(timeout, java.util.concurrent.TimeUnit.SECONDS)
147+
.writeTimeout(timeout, java.util.concurrent.TimeUnit.SECONDS)
148+
.readTimeout(timeout, java.util.concurrent.TimeUnit.SECONDS);
149+
}
150+
142151
Client = client.build();
143152
return Client;
144153
}
@@ -179,22 +188,12 @@ export function request(opts: Https.HttpsRequestOptions): Promise<Https.HttpsRes
179188
));
180189
}
181190

182-
183191
// We have to allow networking on the main thread because larger responses will crash the app with an NetworkOnMainThreadException.
184192
// Note that it would probably be better to offload it to a Worker or (natively running) AsyncTask.
185193
// Also note that once set, this policy remains active until the app is killed.
186194
if (opts.allowLargeResponse) {
187195
android.os.StrictMode.setThreadPolicy(android.os.StrictMode.ThreadPolicy.LAX);
188196
}
189-
190-
//set connection timeout to override okhttp3 default
191-
if (opts.timeout) {
192-
client = client.newBuilder()
193-
.connectTimeout(opts.timeout, java.util.concurrent.TimeUnit.MILLISECONDS)
194-
.writeTimeout(opts.timeout, java.util.concurrent.TimeUnit.MILLISECONDS)
195-
.readTimeout(opts.timeout, java.util.concurrent.TimeUnit.MILLISECONDS)
196-
.build();
197-
}
198197

199198
client.newCall(request.build()).enqueue(new okhttp3.Callback({
200199
onResponse: (task, response) => {

src/https.common.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ export interface HttpsRequestOptions {
2323
* Note that once set to true, this policy remains active until the app is killed.
2424
*/
2525
allowLargeResponse?: boolean;
26+
/**
27+
* Default 10 (seconds).
28+
*/
2629
timeout?: number;
2730
}
2831

src/https.ios.ts

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,6 @@ export function request(opts: Https.HttpsRequestOptions): Promise<Https.HttpsRes
151151
}
152152
manager.requestSerializer.allowsCellularAccess = true;
153153
manager.securityPolicy = (policies.secured === true) ? policies.secure : policies.def;
154-
manager.requestSerializer.timeoutInterval = 10;
155154

156155
let heads = opts.headers;
157156
if (heads) {
@@ -166,10 +165,8 @@ export function request(opts: Https.HttpsRequestOptions): Promise<Https.HttpsRes
166165
Object.keys(cont).forEach(key => dict.setValueForKey(cont[key] as any, key));
167166
}
168167
}
169-
170-
if (opts.timeout) {
171-
manager.requestSerializer.timeoutInterval = opts.timeout / 1000;
172-
}
168+
169+
manager.requestSerializer.timeoutInterval = opts.timeout ? opts.timeout : 10;
173170

174171
let methods = {
175172
'GET': 'GETParametersSuccessFailure',

0 commit comments

Comments
 (0)