Init: Create & Init dayu Project...

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
2019-07-03 15:50:59 +08:00
commit c47137ec4a
92 changed files with 2793 additions and 0 deletions

View File

@@ -0,0 +1,11 @@
export interface ObjectMap {
[key: string]: {};
}
export interface StringMap {
[key: string]: string;
}
export type PortSet = ObjectMap
export type Options = StringMap
export type Config = StringMap
export type Labels = StringMap
export type Ports = StringMap | ObjectMap

View File

@@ -0,0 +1,10 @@
export declare namespace query {
export interface FilterOpt {
filters?: string;
}
export interface LabelOpt {
[key: string]: {
[key: string]: boolean
}
}
}

View File

@@ -0,0 +1,18 @@
import * as common from './common'
export declare namespace container {
export interface ListOpts extends common.query.FilterOpt {
all?: boolean;
limit?: number;
size?: boolean;
}
export interface LogsOpts {
follow?: boolean;
stdout?: boolean;
stderr?: boolean;
since?: number;
until?: number;
timestamps?: boolean;
tail?: number | "all";
}
}

View File

@@ -0,0 +1,5 @@
export * from './swarm'
export * from './common'
export * from './network'
export * from './service'
export * from './container'

View File

@@ -0,0 +1,6 @@
import * as common from './common'
export declare namespace network {
export interface ListOpts extends common.query.FilterOpt {
}
}

View File

@@ -0,0 +1,6 @@
import * as common from './common'
export declare namespace service {
export interface ListOpts extends common.query.FilterOpt {
}
}

View File

@@ -0,0 +1,59 @@
import { Labels } from '../common'
export declare namespace swarm {
type NodeAvailability = string;
export interface InitOpts {
ListenAddr?: string;
AdvertiseAddr?: string;
DefaultAddrPool?: string[];
DataPathAddr?: string;
DataPathPort?: number;
SubnetSize?: number;
ForceNewCluster?: boolean;
Availability?: NodeAvailability;
Spec?: Spec;
}
export interface Spec {
Name?: string;
Labels?: Labels;
Orchestration?: Orchestration;
Raft?: Raft;
Dispatcher?: Dispatcher;
CAConfig?: CAConfig;
TaskDefaults?: TaskDefaults;
EncryptionConfig?: EncryptionConfig;
}
export interface Version {
Index: number;
}
export interface Orchestration {
TaskHistoryRetentionLimit?: number;
}
export interface Raft {
SnapshotInterval?: number;
KeepOldSnapshots?: number;
LogEntriesForSlowFollowers?: number;
ElectionTick?: number;
HeartbeatTick?: number;
}
export interface Dispatcher {
HeartbeatPeriod?: number;
}
export interface CAConfig {
NodeCertExpiry?: number;
}
export interface TaskDefaults {
}
export interface EncryptionConfig {
AutoLockManagers?: boolean;
}
}

View File

@@ -0,0 +1,300 @@
import { Labels, Config as CommonConfig, Ports, Options, StringMap, ObjectMap } from '../common'
export declare namespace container {
export interface ContainerState {
Status: string;
Running: boolean;
Paused: boolean;
Restarting: boolean;
OOMKilled: boolean;
Dead: boolean;
Pid: number;
ExitCode: number;
Error: string;
StartedAt: string;
FinishedAt: Date;
}
export interface LogConfig {
Type: string;
Config: CommonConfig;
}
export interface PortBindings {
}
export interface RestartPolicy {
Name: string;
MaximumRetryCount: number;
}
// WeightDevice is a structure that holds device:weight pair
export interface WeightDevice {
Path: string;
Weight: number;
}
// ThrottleDevice is a structure that holds device:rate_per_second pair
export interface ThrottleDevice {
Path: string;
Rate: number;
}
// DeviceMapping represents the device mapping between the host and the container.
export interface DeviceMapping {
PathOnHost: string;
PathInContainer: string;
CgroupPermissions: string;
}
// DeviceRequest represents a request for devices from a device driver.
// Used by GPU device drivers.
export interface DeviceRequest {
Driver: string // Name of device driver
Count: number // Number of devices to request (-1 = All)
DeviceIDs: string[] // List of device IDs as recognizable by the device driver
Capabilities: string[][] // An OR list of AND lists of device capabilities (e.g. "gpu")
Options: StringMap // Options to pass onto the device driver
}
export interface Resources {
CpuShares?: number;
Memory?: number;
NanoCpus?: number;
CgroupParent?: string;
BlkioWeight?: number;
BlkioWeightDevice?: WeightDevice[];
BlkioDeviceReadBps?: ThrottleDevice[];
BlkioDeviceWriteBps?: ThrottleDevice[];
BlkioDeviceReadIOps?: ThrottleDevice[];
BlkioDeviceWriteIOps?: ThrottleDevice[];
CpuPeriod?: number;
CpuQuota?: number;
CpuRealtimePeriod?: number;
CpuRealtimeRuntime?: number;
CpusetCpus?: string;
CpusetMems?: string;
Devices?: DeviceMapping[];
DeviceCgroupRules?: string[];
DeviceRequests: DeviceRequest[];
DiskQuota?: number;
KernelMemory?: number;
MemoryReservation?: number;
MemorySwap?: number;
MemorySwappiness?: any;
OomKillDisable?: boolean;
PidsLimit?: number;
Ulimits?: any;
CpuCount?: number;
CpuPercent?: number;
IOMaximumIOps?: number;
IOMaximumBandwidth?: number;
}
export interface HostConfig extends Resources {
Binds?: any;
ContainerIDFile: string;
LogConfig: LogConfig;
NetworkMode: string;
PortBindings: PortBindings;
RestartPolicy: RestartPolicy;
AutoRemove: boolean;
VolumeDriver: string;
VolumesFrom?: any;
CapAdd?: any;
CapDrop?: any;
Dns?: any;
DnsOptions?: any;
DnsSearch?: any;
ExtraHosts?: any;
GroupAdd?: any;
IpcMode: string;
Cgroup: string;
Links?: any;
OomScoreAdj: number;
PidMode: string;
Privileged: boolean;
PublishAllPorts: boolean;
ReadonlyRootfs: boolean;
SecurityOpt?: any;
UTSMode: string;
UsernsMode: string;
ShmSize: number;
Runtime: string;
ConsoleSize: number[];
Isolation: string;
Mounts: Mount[];
MaskedPaths: string[];
ReadonlyPaths: string[];
}
export interface Data {
LowerDir: string;
MergedDir: string;
UpperDir: string;
WorkDir: string;
}
export interface GraphDriver {
Data: Data;
Name: string;
}
export type ExposedPorts = Ports
// HealthConfig holds configuration settings for the HEALTHCHECK feature.
export interface HealthConfig {
// Test is the test to perform to check that the container is healthy.
// An empty slice means to inherit the default.
// The options are:
// {} : inherit healthcheck
// {"NONE"} : disable healthcheck
// {"CMD", args...} : exec arguments directly
// {"CMD-SHELL", command} : run command with system's default shell
Test: string[];
// Zero means to inherit. Durations are expressed as integer nanoseconds.
Interval: number; // Interval is the time to wait between checks.
Timeout: number; // Timeout is the time to wait before considering the check to have hung.
StartPeriod: number; // The start period for the container to initialize before the retries starts to count down.
// Retries is the number of consecutive failures needed to consider a container as unhealthy.
// Zero means inherit.
Retries: number;
}
export interface Config {
Hostname: string;
Domainname: string;
User: string;
AttachStdin: boolean;
AttachStdout: boolean;
AttachStderr: boolean;
ExposedPorts: ExposedPorts;
Tty: boolean;
OpenStdin: boolean;
StdinOnce: boolean;
Env: string[];
Cmd?: any;
Healthcheck?: HealthConfig;
ArgsEscaped: boolean;
Image: string;
Volumes?: ObjectMap;
WorkingDir: string;
Entrypoint: string[];
NetworkDisabled: boolean;
MacAddress: string;
OnBuild?: any;
Labels: Labels;
StopSignal: string;
StopTimeout: number;
Shell: string[];
}
export interface IPAMConfig {
IPv4Address: string;
}
export interface Networks {
[key: string]: Network
}
export interface NetworkSettings {
Bridge: string;
SandboxID: string;
HairpinMode: boolean;
LinkLocalIPv6Address: string;
LinkLocalIPv6PrefixLen: number;
Ports: Ports;
SandboxKey: string;
SecondaryIPAddresses?: any;
SecondaryIPv6Addresses?: any;
EndpointID: string;
Gateway: string;
GlobalIPv6Address: string;
GlobalIPv6PrefixLen: number;
IPAddress: string;
IPPrefixLen: number;
IPv6Gateway: string;
MacAddress: string;
Networks: Networks;
}
export interface ContainerJSON {
Id: string;
Created: string;
Path: string;
Args: string[];
State: ContainerState;
Image: string;
ResolvConfPath: string;
HostnamePath: string;
HostsPath: string;
LogPath: string;
Name: string;
RestartCount: number;
Driver: string;
Platform: string;
MountLabel: string;
ProcessLabel: string;
AppArmorProfile: string;
ExecIDs?: any;
HostConfig: HostConfig;
GraphDriver: GraphDriver;
Mounts: Mount[];
Config: Config;
NetworkSettings: NetworkSettings;
}
export interface Port {
IP: string;
PrivatePort: number;
PublicPort: number;
Type: string;
}
export interface Network {
IPAMConfig?: IPAMConfig;
Links?: any;
Aliases?: any;
NetworkID: string;
EndpointID: string;
Gateway: string;
IPAddress: string;
IPPrefixLen: number;
IPv6Gateway: string;
GlobalIPv6Address: string;
GlobalIPv6PrefixLen: number;
MacAddress: string;
DriverOpts?: any;
}
export interface SummaryNetworkSettings {
Networks: Networks;
}
export interface Mount {
Type: string;
Name: string;
Source: string;
Destination: string;
Driver: string;
Mode: string;
RW: boolean;
Propagation: string;
}
export interface Container {
Id: string;
Names: string[];
Image: string;
ImageID: string;
Command: string;
Created: number;
Ports: Port[];
Labels: Labels;
State: string;
Status: string;
HostConfig: {
NetworkMode: string;
};
NetworkSettings: SummaryNetworkSettings;
Mounts: Mount[];
}
}

View File

@@ -0,0 +1,6 @@
export * from './node'
export * from './swarm'
export * from './system'
export * from './network'
export * from './service'
export * from './container'

View File

@@ -0,0 +1,70 @@
import { Labels, Options, StringMap } from '../common'
export declare namespace network {
export interface Config {
Subnet: string;
Gateway: string;
}
export interface IPAM {
Driver: string;
Options?: any;
Config: Config[];
}
export interface ConfigFrom {
Network: string;
}
export interface EndpointResource {
Name: string;
EndpointID: string;
MacAddress: string;
IPv4Address: string;
IPv6Address: string;
}
export interface Containers {
[key: string]: EndpointResource;
}
export interface PeerInfo {
Name: string;
IP: string;
}
// Task carries the information about one backend task
export interface Task {
Name: string;
EndpointID: string;
EndpointIP: string;
Info: StringMap;
}
export interface ServiceInfo {
VIP: string;
Ports: string;
LocalLBIndex: number;
Tasks: Task;
}
export interface NetworkResource {
Name: string;
Id: string;
Created: string;
Scope: string;
Driver: string;
EnableIPv6: boolean;
IPAM: IPAM;
Internal: boolean;
Attachable: boolean;
Ingress: boolean;
ConfigFrom: ConfigFrom;
ConfigOnly: boolean;
Containers?: Containers;
Options: Options;
Labels: Labels;
Peers: network.PeerInfo[];
Services: network.ServiceInfo[];
}
}

View File

@@ -0,0 +1,71 @@
import { Labels } from '../common'
export declare namespace node {
export interface Version {
Index: number;
}
export interface Spec {
Labels: Labels;
Role: string;
Availability: string;
}
export interface Platform {
Architecture: string;
OS: string;
}
export interface Resources {
NanoCPUs: number;
MemoryBytes: number;
}
export interface Plugin {
Type: string;
Name: string;
}
export interface Engine {
EngineVersion: string;
Plugins: Plugin[];
}
export interface TLSInfo {
TrustRoot: string;
CertIssuerSubject: string;
CertIssuerPublicKey: string;
}
export interface Description {
Hostname: string;
Platform: Platform;
Resources: Resources;
Engine: Engine;
TLSInfo: TLSInfo;
}
export interface Status {
State: string;
Addr: string;
}
export interface ManagerStatus {
Leader: boolean;
Reachability: string;
Addr: string;
}
export interface Node {
ID: string;
Version: Version;
CreatedAt: string;
UpdatedAt: string;
Spec: Spec;
Description: Description;
Status: Status;
ManagerStatus: ManagerStatus;
}
}

View File

@@ -0,0 +1,195 @@
import { Labels, Options } from '../common'
export declare namespace service {
export interface Version {
Index: number;
}
export interface Privileges {
CredentialSpec?: any;
SELinuxContext?: any;
}
export interface DriverConfig {
Options: Options;
}
export interface VolumeOptions {
Labels: Labels;
DriverConfig: DriverConfig;
}
export interface Mount {
Type: string;
Source: string;
Target: string;
VolumeOptions: VolumeOptions;
ReadOnly?: boolean;
}
export interface File {
Name: string;
UID: string;
GID: string;
Mode: number;
}
export interface Secret {
File: File;
SecretID: string;
SecretName: string;
}
export interface DNSConfig {
}
export interface ContainerSpec {
Image: string;
Labels: Labels;
Privileges: Privileges;
Mounts: Mount[];
Isolation: string;
Env: string[];
Secrets: Secret[];
Args: string[];
StopGracePeriod?: number;
DNSConfig: DNSConfig;
User: string;
}
export interface Limits {
MemoryBytes: any;
NanoCPUs?: number;
}
export interface Reservations {
MemoryBytes: any;
NanoCPUs?: number;
}
export interface Resources {
Limits: Limits;
Reservations: Reservations;
}
export interface Platform {
Architecture: string;
OS: string;
}
export interface Placement {
Constraints: string[];
Platforms: Platform[];
}
export interface Network {
Target: string;
Aliases: string[];
}
export interface RestartPolicy {
Condition: string;
Delay: any;
MaxAttempts: number;
Window: any;
}
export interface LogDriver {
Name: string;
Options: Options;
}
export interface TaskTemplate {
ContainerSpec: ContainerSpec;
Resources: Resources;
Placement: Placement;
Networks: Network[];
ForceUpdate: number;
Runtime: string;
RestartPolicy: RestartPolicy;
LogDriver: LogDriver;
}
export interface Replicated {
Replicas: number;
}
export interface Global {
}
export interface Mode {
Replicated: Replicated;
Global: Global;
}
export interface Port {
Protocol: string;
TargetPort: number;
PublishedPort: number;
PublishMode: string;
}
export interface EndpointSpec {
Mode: string;
Ports: Port[];
}
export interface UpdateConfig {
Parallelism: number;
FailureAction: string;
Monitor: number;
MaxFailureRatio: number;
Order: string;
}
export interface RollbackConfig {
Parallelism: number;
FailureAction: string;
Monitor: number;
MaxFailureRatio: number;
Order: string;
}
export interface Spec {
Name: string;
Labels: Labels;
TaskTemplate: TaskTemplate;
Mode: Mode;
EndpointSpec: EndpointSpec;
UpdateConfig: UpdateConfig;
RollbackConfig: RollbackConfig;
}
export interface VirtualIP {
NetworkID: string;
Addr: string;
}
export interface Endpoint {
Spec: Spec;
Ports: Port[];
VirtualIPs: VirtualIP[];
}
export interface PreviousSpec {
Name: string;
Labels: Labels;
TaskTemplate: TaskTemplate;
Mode: Mode;
EndpointSpec: EndpointSpec;
UpdateConfig: UpdateConfig;
RollbackConfig: RollbackConfig;
}
export interface Service {
ID: string;
Version: Version;
CreatedAt: string;
UpdatedAt: any;
Spec: Spec;
Endpoint: Endpoint;
PreviousSpec: PreviousSpec;
}
}

View File

@@ -0,0 +1,70 @@
export declare namespace swarm {
export interface Version {
Index: number;
}
export interface Labels {
}
export interface Orchestration {
TaskHistoryRetentionLimit?: number;
}
export interface Raft {
SnapshotInterval?: number;
KeepOldSnapshots?: number;
LogEntriesForSlowFollowers?: number;
ElectionTick?: number;
HeartbeatTick?: number;
}
export interface Dispatcher {
HeartbeatPeriod?: number;
}
export interface CAConfig {
NodeCertExpiry?: number;
}
export interface TaskDefaults {
}
export interface EncryptionConfig {
AutoLockManagers?: boolean;
}
export interface Spec {
Name?: string;
Labels?: Labels;
Orchestration?: Orchestration;
Raft?: Raft;
Dispatcher?: Dispatcher;
CAConfig?: CAConfig;
TaskDefaults?: TaskDefaults;
EncryptionConfig?: EncryptionConfig;
}
export interface TLSInfo {
TrustRoot: string;
CertIssuerSubject: string;
CertIssuerPublicKey: string;
}
export interface JoinTokens {
Worker: string;
Manager: string;
}
export interface Info {
ID: string;
Version: Version;
CreatedAt: string;
UpdatedAt: string;
Spec: Spec;
TLSInfo: TLSInfo;
RootRotationInProgress: boolean;
DefaultAddrPool: string[];
SubnetSize: number;
JoinTokens: JoinTokens;
}
}

View File

@@ -0,0 +1,224 @@
import { Labels, Options } from '../common'
export declare namespace system {
export class Plugins {
Volume: string[];
Network: string[];
Authorization?: any;
Log: string[];
}
export class DockerIo {
Name: string;
Mirrors: string[];
Secure: boolean;
Official: boolean;
}
export class IndexConfigs {
[key: string]: DockerIo;
}
export class RegistryConfig {
AllowNondistributableArtifactsCIDRs: any[];
AllowNondistributableArtifactsHostnames: any[];
InsecureRegistryCIDRs: string[];
IndexConfigs: IndexConfigs;
Mirrors: string[];
}
export class Runc {
path: string;
}
export class Runtimes {
runc: Runc;
}
export class RemoteManager {
NodeID: string;
Addr: string;
}
export class ClusterVersion {
Index: number;
}
export class Orchestration {
TaskHistoryRetentionLimit: number;
}
export class Raft {
SnapshotInterval: number;
KeepOldSnapshots: number;
LogEntriesForSlowFollowers: number;
ElectionTick: number;
HeartbeatTick: number;
}
export class Dispatcher {
HeartbeatPeriod: number;
}
export class CAConfig {
NodeCertExpiry: number;
}
export class TaskDefaults {
}
export class EncryptionConfig {
AutoLockManagers: boolean;
}
export class Spec {
Name: string;
Labels: Labels;
Orchestration: Orchestration;
Raft: Raft;
Dispatcher: Dispatcher;
CAConfig: CAConfig;
TaskDefaults: TaskDefaults;
EncryptionConfig: EncryptionConfig;
}
export class TLSInfo {
TrustRoot: string;
CertIssuerSubject: string;
CertIssuerPublicKey: string;
}
export class Cluster {
ID: string;
Version: ClusterVersion;
CreatedAt: string;
UpdatedAt: string;
Spec: Spec;
TLSInfo: TLSInfo;
RootRotationInProgress: boolean;
DefaultAddrPool: string[];
SubnetSize: number;
}
export class Swarm {
NodeID: string;
NodeAddr: string;
LocalNodeState: string;
ControlAvailable: boolean;
Error: string;
RemoteManagers: RemoteManager[];
Nodes: number;
Managers: number;
Cluster: Cluster;
}
export class ContainerdCommit {
ID: string;
Expected: string;
}
export class RuncCommit {
ID: string;
Expected: string;
}
export class InitCommit {
ID: string;
Expected: string;
}
export class Info {
ID: string;
Containers: number;
ContainersRunning: number;
ContainersPaused: number;
ContainersStopped: number;
Images: number;
Driver: string;
DriverStatus: string[][];
SystemStatus?: any;
Plugins: Plugins;
MemoryLimit: boolean;
SwapLimit: boolean;
KernelMemory: boolean;
CpuCfsPeriod: boolean;
CpuCfsQuota: boolean;
CPUShares: boolean;
CPUSet: boolean;
IPv4Forwarding: boolean;
BridgeNfIptables: boolean;
BridgeNfIp6tables: boolean;
Debug: boolean;
NFd: number;
OomKillDisable: boolean;
NGoroutines: number;
SystemTime: string;
LoggingDriver: string;
CgroupDriver: string;
NEventsListener: number;
KernelVersion: string;
OperatingSystem: string;
OSType: string;
Architecture: string;
IndexServerAddress: string;
RegistryConfig: RegistryConfig;
NCPU: number;
MemTotal: number;
GenericResources?: any;
DockerRootDir: string;
HttpProxy: string;
HttpsProxy: string;
NoProxy: string;
Name: string;
Labels: string[];
ExperimentalBuild: boolean;
ServerVersion: string;
ClusterStore: string;
ClusterAdvertise: string;
Runtimes: Runtimes;
DefaultRuntime: string;
Swarm: Swarm;
LiveRestoreEnabled: boolean;
Isolation: string;
InitBinary: string;
ContainerdCommit: ContainerdCommit;
RuncCommit: RuncCommit;
InitCommit: InitCommit;
SecurityOptions: string[];
ProductLicense: string;
Warnings?: any;
}
export class Platform {
Name: string;
}
export class Details {
ApiVersion: string;
Arch: string;
BuildTime: string;
Experimental: string;
GitCommit: string;
GoVersion: string;
KernelVersion: string;
MinAPIVersion: string;
Os: string;
}
export class Component {
Name: string;
Version: string;
Details: Details;
}
export class Version {
Platform: Platform;
Components: Component[];
Version: string;
ApiVersion: string;
MinAPIVersion: string;
GitCommit: string;
GoVersion: string;
Os: string;
Arch: string;
KernelVersion: string;
BuildTime: string;
}
}

View File

@@ -0,0 +1,23 @@
import * as api from '../utils/api';
import * as opts from '../api/opts'
import * as types from '../api/types'
import * as http from 'http'
export namespace container {
export async function list(filters?: opts.container.ListOpts) {
return await api.get<types.container.Container[]>('/containers/json', filters)
}
export async function info(id: string, query: { size: boolean } = { size: false }) {
return await api.get<types.container.ContainerJSON>(`/containers/${id}/json`, query);
}
export async function logs(id: string, opts: opts.container.LogsOpts = {}): Promise<http.ServerResponse> {
return await api.stream(`/containers/${id}/logs`, Object.assign({
follow: true,
stdout: true,
stderr: true,
tail: 10
}, opts));
}
}

View File

@@ -0,0 +1,6 @@
export * from './node'
export * from './swarm'
export * from './system'
export * from './network'
export * from './service'
export * from './container'

View File

@@ -0,0 +1,9 @@
import * as api from '../utils/api'
import * as opts from '../api/opts'
import * as types from '../api/types'
export namespace network {
export async function list(opts?: opts.network.ListOpts) {
return await api.get<types.network.NetworkResource[]>('/networks', opts)
}
}

View File

@@ -0,0 +1,8 @@
import * as api from '../utils/api'
import * as types from '../api/types'
export namespace node {
export async function list() {
return await api.get<types.node.Node[]>('/nodes');
}
}

View File

@@ -0,0 +1,9 @@
import * as api from '../utils/api';
import * as opts from '../api/opts';
import * as types from '../api/types';
export namespace service {
export async function list(filters?: opts.service.ListOpts) {
return await api.get<types.service.Service[]>('/services', filters);
}
}

View File

@@ -0,0 +1,13 @@
import * as api from '../utils/api'
import * as opts from '../api/opts'
import * as types from '../api/types'
export namespace swarm {
export async function inspect() {
return await api.get<types.swarm.Info>('/swarm');
}
export async function init(opts: opts.swarm.InitOpts) {
return await api.post<string>('/swarm/init', opts);
}
}

View File

@@ -0,0 +1,22 @@
import * as api from '../utils/api'
import * as types from '../api/types'
export namespace system {
export async function info() {
return await api.get<types.system.Info>('/info');
}
export async function version() {
return await api.get<types.system.Version>('/version');
}
export async function events(cb: (events: object) => void) {
let stream = await api.stream<any>('/events');
stream.on('data', (chunk: ArrayBuffer) => {
cb(JSON.parse(Buffer.from(chunk).toString()))
})
stream.on('end', () => {
cb(undefined);
})
}
}

View File

@@ -0,0 +1 @@
export * from './client'

View File

@@ -0,0 +1,78 @@
import * as http from 'http'
import axios, { AxiosResponse, AxiosRequestConfig, Method, AxiosInstance } from 'axios'
let api: AxiosInstance;
export async function get<T>(path: string, data?: object): Promise<T> {
return await handle<T>("GET", path, { params: data });
}
export async function post<T>(path: string, data?: object): Promise<T> {
return await handle<T>("POST", path, { data });
}
export async function stream<T = http.ServerResponse>(path: string, data?: object): Promise<T> {
return await handle<T>("GET", path, { params: data, responseType: "stream" });
}
async function handle<T>(method: Method, path: string, reqConfig?: AxiosRequestConfig): Promise<T> {
let config: AxiosRequestConfig = {
method,
url: path,
};
let startTime = Date.now();
Object.assign(config, reqConfig)
let response: AxiosResponse;
try {
response = await api.request(config);
return response.data as T
} catch (ex) {
if (!ex.response) { throw ex; }
response = ex.response;
if (response.status > 299 && config.responseType == "stream") {
let stream = response.data;
response.data = await new Promise<T>((resolve, reject) => {
let cache = '';
stream.on('data', (chunk: ArrayBuffer) => {
cache += chunk.toString()
})
stream.on('end', () => {
resolve(JSON.parse(cache) as T);
})
})
}
throw new Error(JSON.stringify(response.data));
} finally {
if (response) {
console.log(`========== Docker API Invoke ==========
REQUEST METHOD : ${method}
REQUEST PATH : ${response.request.path}
REQUEST PARAMS : ${config.params ? JSON.stringify(config.params) : ''}
REQUEST BODY : ${config.data ? JSON.stringify(config.data) : ''}
RESPONSE BODY : ${toString.call(response.data.pipe) === "[object Function]" ? '<Stream>' : JSON.stringify(response.data)}
HANDLE TIME : ${Date.now() - startTime}ms
=======================================`);
}
// console.log(`${method} ${path} HTTP/1.1
// ${config.data ? JSON.stringify(config.data, null, 2) + '\n' : ''}
// HTTP/1.1 ${response.status} ${response.statusText}
// ${config.responseType != 'stream' ? JSON.stringify(response.data, null, 2) : config.responseType}`);
}
}
function init() {
const instanceConfig: AxiosRequestConfig = {
headers: {
'Content-Type': 'application/json'
},
timeout: 5000
}
if (process.env.DOCKER_HOST.startsWith("/")) {
instanceConfig.socketPath = process.env.DOCKER_HOST
} else {
instanceConfig.baseURL = process.env.DOCKER_HOST
}
api = axios.create(instanceConfig)
}
init();

View File

@@ -0,0 +1,3 @@
export function Filters2String(filters: any) {
}