diff --git a/package.json b/package.json index fd4cbba..c024246 100644 --- a/package.json +++ b/package.json @@ -61,6 +61,7 @@ }, "dependencies": { "@cocreate/action": "^1.1.1", + "@cocreate/crud-client": "^1.0.5", "@cocreate/docs": "^1.0.3", "@cocreate/render": "^1.0.2", "@cocreate/socket-client": "^1.0.4", diff --git a/server/WSManager.js b/server/WSManager.js deleted file mode 100644 index c9e6556..0000000 --- a/server/WSManager.js +++ /dev/null @@ -1,162 +0,0 @@ - -const qs = require('querystring'); -const WebSocket = require('ws'); -const url = require("url"); -const EventEmitter = require("events").EventEmitter; - -class WSManager extends EventEmitter{ - constructor() { - super(); - - this.clients = new Map(); - this.prefix = "crud"; - - //. websocket server - this.wss = new WebSocket.Server({noServer: true}); - } - - handleUpgrade(req, socket, head) { - const self = this; - const pathname = url.parse(req.url).pathname; - const url_info = this.getKeyFromUrl(pathname) - - if (url_info.type == this.prefix) { - self.wss.handleUpgrade(req, socket, head, function(ws) { - self.onWebSocket(req, ws, url_info); - }) - return true; - } - return false; - } - - onWebSocket(req, ws, info) { - const self = this; - - this.addClient(ws, info.key); - - ws.on('message', (message) => { - self.onMessage(ws, message, info); - }) - - ws.on('close', function () { - console.log('closed client') - self.removeClient(ws, info.key) - }) - - ws.on("error", () => { - console.log('websocket errror before upgrade'); - self.removeClient(ws, info.key) - }); - - this.send(ws, 'connect', info.key); - - } - - removeClient(ws, key) { - let room_clients = this.clients.get(key) - const index = room_clients.indexOf(ws); - console.log(index) - if (index > -1) { - room_clients.splice(index, 1); - } - - if (room_clients.length == 0) { - this.emit('userStatus', ws, {info: key.replace(`/${this.prefix}/`, ''), status: 'off'}); - } - } - - addClient(ws, key) { - let room_clients = this.clients.get(key); - if (room_clients) { - room_clients.push(ws); - } else { - room_clients = [ws]; - } - this.clients.set(key, room_clients); - - this.emit('userStatus', ws, {info: key.replace(`/${this.prefix}/`, ''), status: 'on'}); - } - - getKeyFromUrl(pathname) { - var path = pathname.split("/"); - var params = { - type: null, - key: pathname - } - if (path.length > 0) { - params.type = path[1]; - } - return params - } - - onMessage(ws, message, roomInfo) { - - try { - - if (message instanceof Buffer) { - this.emit('importFile2DB', ws, message, roomInfo) - return; - } - - const data = JSON.parse(message) - - if (data.action) { - this.emit(data.action, ws, data.data, roomInfo); - } - - } catch(e) { - console.log(e); - } - } - - broadcast(ws, namespace, room, messageType, data, isExact) { - let room_key = this.prefix + "/" + namespace; - if (room) { - room_key += `/${room}`; - } - const responseData =JSON.stringify({ - action: messageType, - data: data - }); - - if (isExact) { - const clients = this.clients.get(room_key); - - if (clients) { - clients.forEach((client) => { - if (ws != client) { - client.send(responseData); - } - }) - } - - } else { - this.clients.forEach((value, key) => { - if (key.includes(room_key)) { - value.forEach(client => { - if (ws != client) { - client.send(responseData); - } - }) - } - }) - - } - - } - - send(ws, messageType, data){ - const responseData = { - action: messageType, - data: data - } - ws.send(JSON.stringify(responseData)); - } - - sendBinary(ws, data) { - ws.send(data, {binary: true}); - } -} - - -module.exports = new WSManager() diff --git a/server/apis/stripe/CoCreate-stripe.js b/server/apis/stripe/CoCreate-stripe.js deleted file mode 100644 index 386a0ee..0000000 --- a/server/apis/stripe/CoCreate-stripe.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict' -var utils= require('../utils'); - -class CoCreateStripe { - constructor(wsManager) { - this.wsManager = wsManager; - this.module_id = "stripe"; - this.init(); - } - - init() { - if (this.wsManager) { - this.wsManager.on(this.module_id, (socket, data) => this.sendStripe(socket, data)); - } - } - - async sendStripe(socket, data) { - let type = data['type']; - const stripe = require('stripe')('sk_test_4eC39HqLyjWDarjtT1zdp7dc'); - switch (type) { - case 'stripeGetBalance': - this.stripeGetBalance(socket, type, stripe); break; - case 'stripeBalanceTranscation': - await this.stripeBalanceTranscation(socket, type, stripe); break; - case 'stripeListCustomers': - await this.stripeListCustomers(socket, type, stripe); break; - } - } - - stripeGetBalance (socket, type, stripe) { - stripe.balance.retrieve((err, balance) => { - if (!err && balance) { - utils.send_response(this.wsManager,socket,{"type":type,"response":balance},this.module_id) - } else if (err) { - utils.send_response(this.wsManager,socket,{"type":type,"response":0},this.module_id) - } - }); - } - - async stripeBalanceTranscation(socket, type, stripe) { - const balanceTransaction = await stripe.balanceTransactions.retrieve( - 'txn_1032HU2eZvKYlo2CEPtcnUvl' - ); - utils.send_response(this.wsManager,socket,{"test":type,"response":balanceTransaction},this.module_id) - } - - async stripeListCustomers(socket, type, stripe) { - const customers = await stripe.customers.list({limit: 20}); - utils.send_response(this.wsManager,socket,{"type":type,"response":customers}, this.module_id) - } - -}//end Class -module.exports = CoCreateStripe; diff --git a/server/apis/utils/index.js b/server/apis/utils/index.js deleted file mode 100644 index f64a604..0000000 --- a/server/apis/utils/index.js +++ /dev/null @@ -1,21 +0,0 @@ - -var send_response=(wsManager,socket,obj,send_response)=>{ - console.log("Response TO-> "+send_response) - //console.log("Object ->", obj) - //socket.emit(send_response,obj) - wsManager.send(socket, send_response, obj) -} - - -var send_error=(wsManager,socket,obj,send_response)=>{ - // console.log("error ",obj) - let result = obj; - // delete result.error['request'];// when error, obj too large - // let result = {type:obj.type, error:obj.error}; - //socket.emit(send_response,result) - wsManager.send(socket, send_response, obj) - //res.send(obj); -} - -module.exports.send_response = send_response; -module.exports.send_error = send_error; \ No newline at end of file diff --git a/server/apis/xxx/CoCreate-xxx.js b/server/apis/xxx/CoCreate-xxx.js deleted file mode 100644 index 16adb5a..0000000 --- a/server/apis/xxx/CoCreate-xxx.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict' -var utils= require('../utils'); - -class CoCreateXXX { - constructor(wsManager) { - this.wsManager = wsManager; - this.init(); - - } - - init() { - if (this.wsManager) { - this.wsManager.on('xxx', (socket, data) => this.sendXXX(socket, data)); - } - } - async sendXXX(socket, data) { - let that = this; - let send_response ='xxx'; - let type = data['type']; - - switch (type) { - case 'CreateCustomerBtn': - this.CreateCustomer(socket, type, {}); - break; - } - - }// end sendStripe - - CreateCustomer(socket, type, param1) { - ///... Get result by processing - var result = {}; - utils.send_response(this.wsManager, socket, {"type":type,"response":result}, this.module_id) - } - -}//end Class -module.exports = CoCreateXXX; diff --git a/server/crud.js b/server/crud.js deleted file mode 100644 index 96d8344..0000000 --- a/server/crud.js +++ /dev/null @@ -1,6 +0,0 @@ - -const CoCreateXXX = require('./apis/xxx/Cocreate-xxx') - -module.exports.WSManager = function(manager) { - new CoCreateXXX(manager) -} diff --git a/server/index.js b/server/index.js deleted file mode 100644 index db6009e..0000000 --- a/server/index.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -const express = require('express'); -const { createServer } = require('http'); -const crudController = require("./crud") -const wsManager = require("./WSManager") - -const app = express(); -app.use(express.static('public')); - -// app.use('/', require('./routes/index')); - -// app.use('/stripe', require('./routes/stripe')); -crudController.WSManager(wsManager); -const server = createServer(app); -server.on('upgrade', function upgrade(request, socket, head) { - - if (!wsManager.handleUpgrade(request, socket, head)) { - socket.destroy(); - } -}); - -server.listen(8081); diff --git a/src/CoCreate-action-render.js b/src/CoCreate-action-render.js deleted file mode 100644 index 00f7112..0000000 --- a/src/CoCreate-action-render.js +++ /dev/null @@ -1,22 +0,0 @@ -import CoCreateApi from '@cocreate/api' - -const CoCreateXXX = { - id: 'key', - actions: [ - 'renderKey' - ], - - - action_renderKey: function(element) { - const container = element.closest("form") || document; - let data = CoCreate.api.getFormData(this.id, 'renderKey', container); - console.log(data) - CoCreate.api.render('renderKey', {data: data}); - } -} - - -CoCreateApi.init({ - name: CoCreateXXX.id, - module: CoCreateXXX -}) \ No newline at end of file diff --git a/src/CoCreate-stripe.js b/src/CoCreate-stripe.js deleted file mode 100644 index a9bd360..0000000 --- a/src/CoCreate-stripe.js +++ /dev/null @@ -1,29 +0,0 @@ - -const CoCreateStripe = { - id: 'stripe', - actions: [ - 'getBalance', - 'balanceTransaction', - 'createCustomer', - 'createCard', - 'listCustomers', - 'preTesting' - ], - - render_getBalanceBtn: function(data) { - console.log(data); - }, - render_balanceTransactionBtn: function(data) { - console.log(data); - }, - render_preTesting: function(data) { - console.log(data) - }, - - action_preTesting: function(element) { - - } -} - - -CoCreateApi.register(CoCreateStripe.id, CoCreateStripe); \ No newline at end of file diff --git a/src/CoCreate-xxx.js b/src/CoCreate-xxx.js deleted file mode 100644 index 8a23c6b..0000000 --- a/src/CoCreate-xxx.js +++ /dev/null @@ -1,70 +0,0 @@ -import api from '@cocreate/api' - -const CoCreateXXX = { - id: 'xxx', - actions: [ - 'xxxGetKeysFromBd', - 'xxxRender', - 'xxxCreateCard', - ], - - /** - * - * CoCreate-xxx action chain - * Ex: action name: xxxCreateRequest - * 1. call action_xxxCreateRequest() function - * - get the data from form - * - send data and action into server - * 2. Server processing - * 3. Received the response from server - * 4. If render_xxxCreateRequest function exist, call render_xxxCreateRequest() function - * 5. Fire the event for end (event name is xxxCreateRequest) - * 6. Run the next action by cocreate-action - * - **/ - - /** - * ---------- Render-processing function ----------------- - * When receive response, these function will call. - * - * These functions has name rule - * --- rule: render_{actionname}(data) {} - * - **/ - - render_xxxGetKeysFromBd: function(data) { - console.log(JSON.stringify(data)); - }, - - render_xxxCreateCard: function(data) { - console.log('Card --- ', data); - }, - - - /** - * --------- Action processing function ----------- - * These function will call by cocreate-render when click button (data-actions) - * - * Action functions has name rule - * ---- rule: action_{actionname}(element[, data]) {} - * - * Input parameter: - * element: Dom Element (actioin button) - * data: data from before stage action - * - * - **/ - - action_xxxRender: function(element, data) { - //. data rendering by cocreate-render - api.render(this.id, 'xxxCreateCard', {render2: data}); - }, - -} - -api.init({ - name: CoCreateXXX.id, - module: CoCreateXXX -}) - -export default CoCreateXXX; \ No newline at end of file diff --git a/src/archive/index.1.js b/src/client.js similarity index 98% rename from src/archive/index.1.js rename to src/client.js index 346defb..ed7c709 100644 --- a/src/archive/index.1.js +++ b/src/client.js @@ -1,4 +1,4 @@ -import CoCreateSocket from "@cocreate/socket" +import CoCreateSocket from "@cocreate/socket-client" import CoCreateAction from '@cocreate/action' import CoCreateRender from '@cocreate/render' diff --git a/src/index.js b/src/index.js index ed7c709..2cd1b47 100644 --- a/src/index.js +++ b/src/index.js @@ -1,212 +1,14 @@ -import CoCreateSocket from "@cocreate/socket-client" -import CoCreateAction from '@cocreate/action' -import CoCreateRender from '@cocreate/render' - -let socketApi = new CoCreateSocket('api'); - -const CoCreateApi = { - modules: { }, - - init: function({name, module}) { - this.register(name, module) - }, - - register: function(name, m_instance) { - const self = this; - if (typeof this.modules[name] === 'undefined') { - this.modules[name] = m_instance; - - socketApi.listen(name, (data) => { - self.__responseProcess(name, data); - }) - - //. register actions - - if (Array.isArray(m_instance['actions'])) { - m_instance['actions'].forEach((action) => { - if (typeof m_instance[`action_${action}`] !== 'function') { - m_instance[`action_${action}`] = function(element) { - self.__commonAction(m_instance.id, action, element) - } - } - CoCreateAction.init({ - action: action, - endEvent: action, - callback: (btn) => { - m_instance[`action_${action}`](btn); - }, - }) - }) - } - } - }, - - __responseProcess: function(m_name, data) { - const {type, response} = data; - const m_instance = this.modules[m_name] - - if (type && response && m_instance) { - - if ( typeof m_instance[`render_${type}`] === 'function') { - m_instance[`render_${type}`](response); - } - - this.render(type, response); - - document.dispatchEvent(new CustomEvent(type, { - detail: { - data: response - } - })) - } - }, - - __commonAction: function(id, action, element) { - const container = element.closest("form") || document; - let data = CoCreateApi.getFormData(id, action, container); - CoCreateApi.send(id, action, data); - }, - - - getFormData : function(m_name, action, container){ - const mainAttr = `data-${m_name}`; - const self = this; - const elements = container.querySelectorAll(`[${mainAttr}^="${action}."]`); - - let data = {} - elements.forEach(element => { - let name = element.getAttribute(mainAttr); - let array_name = element.getAttribute(mainAttr + "_array"); - let value = self.__getElValue(element); - - if (!name) return - - if (action) { - let re = new RegExp(`^${action}.`, 'i'); - if (re.test(name)) { - name = name.replace(re, ""); - } else { - return; - } - } - - if (array_name) { - if (!data[name]) { - data[name] = []; - } - data[name].push(self.getFormData(m_name, array_name, element)); - } else if (value != null) { - data[name] = value; - } - }); - - let keys = Object.keys(data) - let objectData = {}; - keys.forEach((k) => { - if (k.split('.').length > 1) { - let newData = self.__createObject(data[k], k); - delete data[k] - - objectData = self.__mergeObject(objectData, newData); - } else { - objectData[k] = data[k]; - } - }) - return objectData; - }, - - __getElValue: function(element) { - let value = null; - if (typeof element.value !== "undefined") { - switch (element.type.toLocaleLowerCase()) { - case 'checkbox': - if (element.checked) { - value = element.value - } - break; - default: - value = element.value; - break; - } - } else { - value = element.getAttribute('value'); - if (!value) { - value = element.innerHTML; - } - } - - return value; - }, - - __mergeObject: function(target, source) { - target = target || {}; - for (let key of Object.keys(source)) { - if (source[key] instanceof Object) { - Object.assign(source[key], this.__mergeObject(target[key], source[key])) - } - } - - Object.assign(target || {}, source) - return target - }, - - __createObject: function (data, path) { - if (!path) return data; - - let keys = path.split('.') - let newObject = data; - - for (var i = keys.length - 1; i >= 0; i--) { - newObject = {[keys[i]]: newObject} - } - return newObject; - }, - - send : function(module, action, data){ - let request_data = this.getCommonParamsExtend(data || {}); - request_data = {...request_data, data}; - socketApi.send(module, {type: action, data: request_data}); - }, - - render: function(action, data) { - CoCreateRender.data({ - selector: `[data-template_id="${action}"]`, - data: data - }); - }, - - createApiSocket: function(host, namespace) { - if (namespace) { - socketApi.create({ - namespace: namespace, - room: null, - host: host - }); - socketApi.setGlobalScope(namespace); - } else { - socketApi.create({ - namespace: null, - room: null, - host: host - }); - } - }, - - getCommonParamsExtend: function(info) - { - return { - "apiKey": info.apiKey || config.apiKey, - "securityKey": info.securityKey || config.securityKey, - "organization_id": info.organization_id || config.organization_Id, - } - } -} - -CoCreateApi.createApiSocket( - window.config.host ? window.config.host : 'server.cocreate.app', - window.config.organization_Id - // window.config.apiKey - // window.config.securityKey -); - -export default CoCreateApi; \ No newline at end of file +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + define(["./client"], function(CoCreateApi) { + return factory(CoCreateApi) + }); + } else if (typeof module === 'object' && module.exports) { + const CoCreateApi = require("./server.js") + module.exports = factory(CoCreateApi); + } else { + root.returnExports = factory(root["./client.js"]); + } +}(typeof self !== 'undefined' ? self : this, function (CoCreateApi) { + return CoCreateApi; +})); \ No newline at end of file diff --git a/src/server.js b/src/server.js new file mode 100644 index 0000000..a48bdd4 --- /dev/null +++ b/src/server.js @@ -0,0 +1,142 @@ +const crud = require('@cocreate/crud-client') +const CoCreateSocketClient = require('@cocreate/socket-client') +let socket = new CoCreateSocketClient("ws"); + +crud.setSocket(socket); + +var api = ( ()=> { + return { + send_response : (wsManager,socket,obj,send_response) => { + console.log("Response TO-> "+send_response) + wsManager.send(socket, send_response, obj) + }, + + handleError : (wsManager,socket, type, error,module_id)=>{ + const response = { + 'object': 'error', + 'data':error || error.response || error.response.data || error.response.body || error.message || error, + }; + this.send_response(wsManager, socket, { type, response }, module_id); + }, + getOrg : async (config, module) =>{ + console.log("config WS utils ==== ",config) + const socket_config = { + "config": { + "apiKey": config["apiKey"], + "securityKey": config["securityKey"], + "organization_id": config["organization_id"], + }, + "prefix": "ws", + "host": "server.cocreate.app:8088" + } + socket.create({ + namespace: socket_config.config.organization_id, + room: null, + host: socket_config.host + }) + const event = "getOrg"; + + crud.readDocument({ + collection: "organizations", + document_id: config["organization_id"], + event, + apiKey: config["apiKey"], + securityKey: config["securityKey"], + organization_id: config["organization_id"] + }); + let org_row = await crud.listenAsync(event); + console.log(org_row) + try{ + org_row =org_row["data"]; + }catch(e){ + console.log(module," Error GET ORG in : ",e); + return false; + } + return org_row; + }, + getOrgInRoutesbyHostname : async (config, hostname) =>{ + var socket_config = { + "config": { + "apiKey": config["config"]["apiKey"], + "securityKey": config["config"]["securityKey"], + "organization_Id": config["config"]["organization_id"], + }, + "prefix": "ws", + "host": "server.cocreate.app:8088" + }; + + socket.create({ + namespace: socket_config.config.organization_Id, + room: null, + host: socket_config.host + }) + + let eventGetOrg = "getOrginMaster"; + + crud.readDocumentList({ + collection: "organizations", + operator: { + filters: [{ + name: 'domains', + operator: "$in", + value: [hostname] + }], + orders: [], + startIndex: 0, + search: { type: 'or', value: []} + }, + event: eventGetOrg, + is_collection: false, + apiKey: config["config"]["apiKey"], + securityKey: config["config"]["securityKey"], + organization_id: config["config"]["organization_id"] + }); + + let data2 = await crud.listenAsync(eventGetOrg); + console.log("data2 ===",data2) + + var org = data2["data"][0] + + var socket_config = { + "config": { + "apiKey": org["apiKey"], + "securityKey": org["securityKey"], + "organization_Id": org["_id"].toString(), + }, + "prefix": "ws", + "host": "server.cocreate.app:8088" + } + //other connection + socket.create({ + namespace: socket_config.config.organization_Id, + room: null, + host: socket_config.host + }) + // socket.setGlobalScope(socket_config.config.organization_id) + crud.readDocumentList({ + collection: "organizations", + operator: { + filters: [{ + name: '_id', + operator: "$eq", + value: [org["_id"].toString()] + }], + orders: [], + startIndex: 0, + search: { type: 'or', value: []} + }, + "event": "getDataOrg", + is_collection: false, + apiKey: org["apiKey"], + securityKey: org["securityKey"], + organization_id: org["_id"] + }); + let myOrg = await crud.listenAsync("getDataOrg"); + let result = {'row':myOrg,'socket_config':socket_config}; + return result; + } + + } // +})(); + +module.exports = api; \ No newline at end of file diff --git a/yarn.lock b/yarn.lock index 30dfc5c..a4bb681 100644 --- a/yarn.lock +++ b/yarn.lock @@ -839,6 +839,15 @@ "@cocreate/docs" "^1.0.3" mini-css-extract-plugin "^1.5.0" +"@cocreate/crud-client@^1.0.5": + version "1.0.5" + resolved "https://registry.yarnpkg.com/@cocreate/crud-client/-/crud-client-1.0.5.tgz#66c54ae6ebd72fa6dcaf93caf2ffc866294143a0" + integrity sha512-6WFm6Dh+JHT+Lza5W3dQ4W0Hm35CozYhRdk/dwe/LR+zUQRpUIUxTLkqGntlGk8BmPn+jJdrJFIRRo5jGPzpPg== + dependencies: + "@cocreate/docs" "^1.0.3" + "@cocreate/socket-client" "^1.0.2" + mini-css-extract-plugin "^1.5.0" + "@cocreate/docs@^1.0.3": version "1.1.2" resolved "https://registry.yarnpkg.com/@cocreate/docs/-/docs-1.1.2.tgz#3ed93927574e400d2a832651f6d3c32f46ab38b3" @@ -857,7 +866,7 @@ "@cocreate/docs" "^1.0.3" mini-css-extract-plugin "^1.5.0" -"@cocreate/socket-client@^1.0.4": +"@cocreate/socket-client@^1.0.2", "@cocreate/socket-client@^1.0.4": version "1.0.4" resolved "https://registry.yarnpkg.com/@cocreate/socket-client/-/socket-client-1.0.4.tgz#375f07f7134f564d6faf83b3d850fd276db19ff2" integrity sha512-ChZIqIqcgozeNPH2w1KoX0f8kFavmudnROi9V5kgUWq9o2qMqW2bPktsachEPFUawxpjkymYHQu4FT1TxLUnWw==