Skip to content

Instantly share code, notes, and snippets.

@andrewborisov
Last active August 18, 2020 00:07
Show Gist options
  • Save andrewborisov/24dc76674f68c5a34ec451aae58d91fc to your computer and use it in GitHub Desktop.
Save andrewborisov/24dc76674f68c5a34ec451aae58d91fc to your computer and use it in GitHub Desktop.
Гист для статьи: "Еще раз о паттернах проектирования в Javascript es6 (часть 2)"
class WebsocketInteraction {
constructor(url, port) {
this.url = url;
this.port = port;
}
connect() {
return new Promise((resolve) => {
this.connection = new WebSocket(`wss://${this.url}:${this.port}`);
this.connection.onopen = (e) => {
console.log('connected', e);
resolve();
};
});
}
disconnect() {
return new Promise((resolve) => {
this.connection.close();
this.connection.onclose = (e) => {
console.log('disconnected', e);
resolve();
};
});
}
sendMessage(message) {
return new Promise((resolve) => {
this.connection.send(message);
this.connection.onmessage = (e) => {
console.log(e);
resolve();
};
});
}
}
class HttpInteraction {
constructor(url) {
this.url = url;
}
sendRequest(message, method) {
return fetch(`https://${this.url}`, {
method,
body: JSON.stringify(message),
})
.then((res) => res.json())
.then((post) => {
console.log(post);
});
}
}
class ServerInteraction {
request(type, message, method) {
if (type === 'websocket') {
const server = new WebsocketInteraction('echo.websocket.org', 443);
return server.connect()
.then(() => server.sendMessage(message))
.then(() => server.disconnect());
} if (method && type === 'http') {
const server = new HttpInteraction('jsonplaceholder.typicode.com/posts');
return server.sendRequest(message, method);
}
throw new Error('No method provided!');
}
}
const testing = async () => {
const server = new ServerInteraction();
await server.request('websocket', 'test-message');
console.log('=========================');
await server.request('http', {
title: 'foo',
body: 'bar',
userId: 1,
}, 'POST');
};
testing();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment