103 lines
3.2 KiB
TypeScript
103 lines
3.2 KiB
TypeScript
import { generateHMACSignature } from "#middleware/hmac.js";
|
|
import { requestBuilder, shopifyHeaderBuilder } from "#shared/requests.js";
|
|
import { ShopifyEvent, SubscriptionData, SubscriptorData, Topic } from "./subscriptions.types";
|
|
|
|
/**
|
|
* De scheduler tiene poco
|
|
*/
|
|
export class EventScheduler {
|
|
public eventList: SubscriptorData[] = []
|
|
public activeIntervals: NodeJS.Timeout[] = []
|
|
|
|
constructor(args: {
|
|
events?: SubscriptorData[],
|
|
}) {
|
|
if (args.events != undefined) {
|
|
this.eventList = args.events
|
|
}
|
|
this.start()
|
|
}
|
|
|
|
private start() {
|
|
for (const event of this.eventList) {
|
|
let sentMesages = 0
|
|
const interval = setInterval(() => {
|
|
console.log("[Server] Lanzado evento ", event)
|
|
if (event.options?.mesages == undefined || event.options?.mesages < 1)
|
|
return; // Se lannza de continuo
|
|
sentMesages++;
|
|
if (sentMesages > event.options.mesages) {
|
|
clearInterval(interval)
|
|
}
|
|
}, event.options?.period ?? 1000)
|
|
this.activeIntervals.push(interval)
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
export class SubscriptionManager {
|
|
private subscriptions: Map<Topic, SubscriptionData> = new Map<Topic, SubscriptionData>()
|
|
public scheduler: EventScheduler
|
|
|
|
constructor(
|
|
scheduler: EventScheduler,
|
|
subs?: typeof this.subscriptions,
|
|
) {
|
|
this.scheduler = scheduler
|
|
if (subs != undefined) {
|
|
this.subscriptions = subs
|
|
}
|
|
}
|
|
|
|
|
|
public addSubscriber(args: { topic: string, subscriber: SubscriptorData }) {
|
|
const topic = args.topic
|
|
if (topic == undefined) throw new Error("Topic vacio")
|
|
const topicSubscribers = this.subscriptions.get(topic)
|
|
if (topicSubscribers == undefined) {
|
|
this.subscriptions.set(topic, {
|
|
topic,
|
|
subscriptors: [args.subscriber]
|
|
})
|
|
}
|
|
}
|
|
|
|
public poll(event: ShopifyEvent) {
|
|
const topic = event.topic
|
|
|
|
if (!this.subscriptions.has(topic)) {
|
|
console.error("Topic desconocido: " + topic)
|
|
return;
|
|
}
|
|
|
|
const subscriptors = this.subscriptions.get(topic)
|
|
|
|
for (const sub of subscriptors!.subscriptors) {
|
|
const body = {
|
|
id: 1234
|
|
}
|
|
const parsedBody = JSON.stringify(body)
|
|
const signature = generateHMACSignature(parsedBody, sub.secretkey)
|
|
const request = requestBuilder({
|
|
method: sub.method,
|
|
headers: shopifyHeaderBuilder({
|
|
topic: topic,
|
|
signature: signature
|
|
}),
|
|
host: sub.host,
|
|
port: sub.port,
|
|
endpoint: sub.endpoint
|
|
})
|
|
request.write(parsedBody)
|
|
// Data puede venir en chunks!
|
|
request.on("data", () => console.log)
|
|
request.on("end", () => console.log)
|
|
request.on("error", () => console.error)
|
|
|
|
request.end()
|
|
console.debug("Enviado evento a ", sub.host, ":", sub.port, sub.endpoint)
|
|
}
|
|
}
|
|
}
|