Skip to content

Commit

Permalink
refactor example code
Browse files Browse the repository at this point in the history
This commit addresses most of the issues raised in kubernetes-client#1907:

- Migrate from require() to import.
- Migrate from Promises API to async/await.
- Use @kubernetes/client-node instead of dist/
- Add examples specific tslint to allow console.

This commit does not sync the examples from the master branch
to the release-1.x branch.
  • Loading branch information
cjihrig committed Oct 23, 2024
1 parent a7564c5 commit 93587ad
Show file tree
Hide file tree
Showing 29 changed files with 239 additions and 299 deletions.
3 changes: 1 addition & 2 deletions examples/cache-example.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// in a real program use require('@kubernetes/client-node')
const k8s = require('../dist/index');
import * as k8s from '@kubernetes/client-node';

const kc = new k8s.KubeConfig();
kc.loadFromDefault();
Expand Down
17 changes: 7 additions & 10 deletions examples/example.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// in a real program use require('@kubernetes/client-node')
const k8s = require('../dist/index');
import * as k8s from '@kubernetes/client-node';

const kc = new k8s.KubeConfig();
kc.loadFromDefault();
Expand All @@ -8,11 +7,9 @@ const k8sApi = kc.makeApiClient(k8s.CoreV1Api);

const namespace = 'default';

k8sApi
.listNamespacedPod({ namespace })
.then((res) => {
console.log(res);
})
.catch((err) => {
console.error(err);
});
try {
const res = await k8sApi.listNamespacedPod({ namespace });
console.log(res);
} catch (err) {
console.error(err);
}
35 changes: 17 additions & 18 deletions examples/follow-logs.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// in a real program use require('@kubernetes/client-node')
const k8s = require('../dist/index');
const stream = require('stream');
import * as k8s from '@kubernetes/client-node';
import stream from 'node:stream';

const kc = new k8s.KubeConfig();
kc.loadFromDefault();
Expand All @@ -18,19 +17,19 @@ logStream.on('data', (chunk) => {
process.stdout.write(chunk);
});

log.log(namespace, pod, container, logStream, {
follow: true,
tailLines: 50,
pretty: false,
timestamps: false,
})
.catch((err) => {
console.error(err);
})
.then((req) => {
// disconnects after 5 seconds
setTimeout(function () {
//Note: You might have to install AbortController if you are using node version < 15.0.0
req.abort();
}, 5000);
try {
const req = await log.log(namespace, pod, container, logStream, {
follow: true,
tailLines: 50,
pretty: false,
timestamps: false,
});

// disconnects after 5 seconds
setTimeout(() => {
// Note: You might have to install AbortController if you are using Node version < 15.0.0
req.abort();
}, 5000);
} catch (err) {
console.error(err);
}
27 changes: 9 additions & 18 deletions examples/in-cluster-create-job-from-cronjob.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// in a real program use require('@kubernetes/client-node')
const k8s = require('../dist/index');
import * as k8s from '@kubernetes/client-node';

const namespace = 'default';

Expand All @@ -21,19 +20,11 @@ metadata.annotations = {
};
job.metadata = metadata;

batchV1beta1Api
.readNamespacedCronJob({ name: cronJobName, namespace })
.then((cronJobRes) => {
job.spec = cronJobRes?.spec?.jobTemplate.spec;
batchV1Api
.createNamespacedJob({ namespace, body: job })
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
})
.catch((err) => {
console.log(err);
});
try {
const cronJobRes = await batchV1beta1Api.readNamespacedCronJob({ name: cronJobName, namespace });
job.spec = cronJobRes?.spec?.jobTemplate.spec;
const res = await batchV1Api..createNamespacedJob({ namespace, body: job });
console.log(res);
} catch (err) {
console.error(err);
}
18 changes: 8 additions & 10 deletions examples/in-cluster.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// in a real program use require('@kubernetes/client-node')
const k8s = require('../dist/index');
import * as k8s from '@kubernetes/client-node';

const kc = new k8s.KubeConfig();
kc.loadFromCluster();
Expand All @@ -8,11 +7,10 @@ const k8sApi = kc.makeApiClient(k8s.CoreV1Api);

const namespace = 'default';

k8sApi
.listNamespacedPod({ namespace })
.then((res) => {
console.log(res);
})
.catch((err) => {
console.error(err);
});
try {
const res = await k8sApi.listNamespacedPod({ namespace });

console.log(res);
} catch (err) {
console.error(err);
}
62 changes: 32 additions & 30 deletions examples/ingress.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// in a real program use require('@kubernetes/client-node')
const k8s = require('../dist/index');
import * as k8s from '@kubernetes/client-node';

const kc = new k8s.KubeConfig();
kc.loadFromDefault();
Expand All @@ -9,35 +8,38 @@ const k8sApi = kc.makeApiClient(k8s.NetworkingV1Api);
const namespace = 'default';
const clientIdentifier = 'my-subdomain';

k8sApi
.createNamespacedIngress({
namespace,
body: {
apiVersion: 'networking.k8s.io/v1',
kind: 'Ingress',
metadata: { name: `production-custom-${clientIdentifier}` },
spec: {
rules: [
{
host: `${clientIdentifier}.example.com`,
http: {
paths: [
{
backend: {
service: {
name: 'production-auto-deploy',
port: { number: 5000 },
try {
await k8sApi
.createNamespacedIngress({
namespace,
body: {
apiVersion: 'networking.k8s.io/v1',
kind: 'Ingress',
metadata: { name: `production-custom-${clientIdentifier}` },
spec: {
rules: [
{
host: `${clientIdentifier}.example.com`,
http: {
paths: [
{
backend: {
service: {
name: 'production-auto-deploy',
port: { number: 5000 },
},
},
path: '/',
pathType: 'ImplementationSpecific',
},
path: '/',
pathType: 'ImplementationSpecific',
},
],
],
},
},
},
],
tls: [{ hosts: [`${clientIdentifier}.example.com`] }],
],
tls: [{ hosts: [`${clientIdentifier}.example.com`] }],
},
},
},
})
.catch((e) => console.error(e));
})
} catch (e) {
console.error(e);
}
5 changes: 2 additions & 3 deletions examples/kubectl/equivalents/apply.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// in a real program use require('@kubernetes/client-node')
import * as k8s from '../../../dist/index';
import * as k8s from '@kubernetes/client-node';

const kc = new k8s.KubeConfig();
kc.loadFromDefault();
Expand All @@ -19,4 +18,4 @@ const deployment = {
}
}

client.patch(deployment)
client.patch(deployment)
5 changes: 2 additions & 3 deletions examples/kubectl/equivalents/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// in a real program use require('@kubernetes/client-node')
import * as k8s from '../../../dist/index';
import * as k8s from '@kubernetes/client-node';

const kc = new k8s.KubeConfig();
kc.loadFromDefault();
Expand All @@ -12,4 +11,4 @@ const namespace = {
}
}

client.create(namespace)
client.create(namespace)
5 changes: 2 additions & 3 deletions examples/kubectl/equivalents/delete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// in a real program use require('@kubernetes/client-node')
import * as k8s from '../../../dist/index';
import * as k8s from '@kubernetes/client-node';

const kc = new k8s.KubeConfig();
kc.loadFromDefault();
Expand All @@ -12,4 +11,4 @@ const namespace = {
}
}

client.delete(namespace)
client.delete(namespace)
5 changes: 2 additions & 3 deletions examples/kubectl/equivalents/get.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// in a real program use require('@kubernetes/client-node')
import * as k8s from '../../../dist/index';
import * as k8s from '@kubernetes/client-node';

const kc = new k8s.KubeConfig();
kc.loadFromDefault();
Expand All @@ -13,4 +12,4 @@ const namespace = {
}

const live_namespace = (await client.read(namespace)).body
console.log(live_namespace)
console.log(live_namespace)
26 changes: 11 additions & 15 deletions examples/namespace.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// in a real program use require('@kubernetes/client-node')
const k8s = require('../dist/index');
import * as k8s from '@kubernetes/client-node';

const kc = new k8s.KubeConfig();
kc.loadFromDefault();
Expand All @@ -12,16 +11,13 @@ var namespace = {
},
};

k8sApi.createNamespace({ body: namespace }).then(
(response) => {
console.log('Created namespace');
console.log(response);
k8sApi.readNamespace({ name: namespace.metadata.name }).then((response) => {
console.log(response);
k8sApi.deleteNamespace({ name: namespace.metadata.name });
});
},
(err) => {
console.log('Error!: ' + err);
},
);
try {
const response = await k8sApi.createNamespace({ body: namespace });
console.log('Created namespace');
console.log(response);
const res = await k8sApi.readNamespace({ name: namespace.metadata.name });
console.log(res);
await k8sApi.deleteNamespace({ name: namespace.metadata.name });
} catch (err) {
console.error('Error!: ' + err);
}
29 changes: 13 additions & 16 deletions examples/patch-example.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
// in a real program use require('@kubernetes/client-node')
const k8s = require('../dist/index');
const { createConfiguration, ServerConfiguration } = require('../dist');
const { PromiseMiddlewareWrapper } = require('../dist/gen/middleware');
import * as k8s from '@kubernetes/client-node';
import { PromiseMiddlewareWrapper } from '@kubernetes/client-node/dist/gen/middleware.js';

const kc = new k8s.KubeConfig();
kc.loadFromDefault();
Expand All @@ -10,7 +8,8 @@ const k8sApi = kc.makeApiClient(k8s.CoreV1Api);

const namespace = 'default';

k8sApi.listNamespacedPod({ namespace }).then((res) => {
try {
const res = await k8sApi.listNamespacedPod({ namespace });
const patch = [
{
op: 'replace',
Expand All @@ -37,24 +36,22 @@ k8sApi.listNamespacedPod({ namespace }).then((res) => {
throw new Error('Server is undefined');
}

const baseServerConfig = new ServerConfiguration(server, {});
const configuration = createConfiguration({
const baseServerConfig = new k8s.ServerConfiguration(server, {});
const configuration = k8s.createConfiguration({
middleware: [headerPatchMiddleware],
baseServer: baseServerConfig,
authMethods: {
default: kc,
},
});
k8sApi

await k8sApi
.patchNamespacedPod(
{ name: res?.items?.[0].metadata?.name ?? '', namespace, body: patch },
configuration,
)
.then(() => {
console.log('Patched.');
})
.catch((err) => {
console.log('Error: ');
console.log(err);
});
});
console.log('Patched.');
} catch (err) {
console.error('Error: ');
console.error(err);
}
28 changes: 13 additions & 15 deletions examples/raw-example.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// in a real program use require('@kubernetes/client-node')
const k8s = require('../dist/index');
const fetch = require('node-fetch');
const https = require('https');
import * as k8s from '@kubernetes/client-node';
import fetch from 'node-fetch';
import https from 'node:https';

const kc = new k8s.KubeConfig();
kc.loadFromDefault();
Expand All @@ -24,14 +23,13 @@ const opts = {
kc.applyToHTTPSOptions(opts);

const url = `${kc?.getCurrentCluster()?.server}/api/v1/namespaces/default/pods`;
fetch(url, opts)
.then((response) => {
console.log(`statusCode: ${response.status}`);
return response.text();
})
.then((body) => {
console.log(`body: ${body}`);
})
.catch((error) => {
console.log(`error: ${error}`);
});

try {
const response = await fetch(url, opts);
const body = await response.text();

console.log(`statusCode: ${response.status}`);
console.log(`body: ${body}`);
} catch (err) {
console.error(`error: ${error}`);
}
3 changes: 1 addition & 2 deletions examples/scale-deployment.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// in a real program use require('@kubernetes/client-node')
const k8s = require('../dist/index');
import * as k8s from '@kubernetes/client-node';

const kc = new k8s.KubeConfig();
kc.loadFromDefault();
Expand Down
Loading

0 comments on commit 93587ad

Please sign in to comment.