@seeka-labs/cli-apps 2.0.13-alpha.0 → 2.0.19-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/LICENSE +19 -19
  2. package/dist/index.js +1 -1
  3. package/dist/index.js.map +2 -2
  4. package/dist/init-template/.gitlab-ci.yml +46 -46
  5. package/dist/init-template/.yarnrc.yml +8 -0
  6. package/dist/init-template/README.md +6 -6
  7. package/dist/init-template/app/browser/jest.config.js +11 -11
  8. package/dist/init-template/app/browser/package.json +40 -40
  9. package/dist/init-template/app/browser/scripts/esbuild/build-browser-plugin.mjs +110 -110
  10. package/dist/init-template/app/browser/scripts/esbuild/plugins/importAsGlobals.mjs +38 -38
  11. package/dist/init-template/app/browser/src/browser.ts +12 -12
  12. package/dist/init-template/app/browser/src/plugin/index.test.ts +6 -6
  13. package/dist/init-template/app/browser/src/plugin/index.ts +47 -47
  14. package/dist/init-template/app/browser/tsconfig.json +34 -34
  15. package/dist/init-template/app/server-azure-function/.eslintrc.cjs +10 -10
  16. package/dist/init-template/app/server-azure-function/.funcignore +21 -21
  17. package/dist/init-template/app/server-azure-function/README.md +104 -104
  18. package/dist/init-template/app/server-azure-function/host.json +19 -19
  19. package/dist/init-template/app/server-azure-function/local.settings.example.json +25 -25
  20. package/dist/init-template/app/server-azure-function/package.json +52 -52
  21. package/dist/init-template/app/server-azure-function/scripts/ngrok.js +27 -27
  22. package/dist/init-template/app/server-azure-function/src/functions/healthCheck.ts +13 -13
  23. package/dist/init-template/app/server-azure-function/src/functions/pollingExample.ts +39 -39
  24. package/dist/init-template/app/server-azure-function/src/functions/queueExample.ts +66 -66
  25. package/dist/init-template/app/server-azure-function/src/functions/seekaAppWebhook.ts +235 -235
  26. package/dist/init-template/app/server-azure-function/src/lib/browser/index.ts +54 -54
  27. package/dist/init-template/app/server-azure-function/src/lib/jobs/index.ts +95 -95
  28. package/dist/init-template/app/server-azure-function/src/lib/logging/index.ts +92 -92
  29. package/dist/init-template/app/server-azure-function/src/lib/models/index.ts +6 -6
  30. package/dist/init-template/app/server-azure-function/src/lib/services/index.ts +40 -40
  31. package/dist/init-template/app/server-azure-function/src/lib/state/redis/index.ts +96 -96
  32. package/dist/init-template/app/server-azure-function/src/lib/state/seeka/installations.ts +64 -64
  33. package/dist/init-template/app/server-azure-function/tsconfig.json +17 -17
  34. package/dist/init-template/package.json +1 -1
  35. package/dist/init-template/tsconfig.json +25 -25
  36. package/package.json +2 -2
@@ -1,96 +1,96 @@
1
- import { QueueClient } from '@azure/storage-queue';
2
- import { isArray } from 'lodash';
3
- import type { Logger } from 'winston';
4
- import winston from 'winston';
5
-
6
- export interface BackgroundJobRequestContext {
7
- organisationId?: string;
8
- organisationBrandId?: string;
9
- applicationInstallId?: string;
10
- causationId: string
11
- correlationId: string
12
- }
13
-
14
- export const signatureHeaderName = 'x-signature-hmac';
15
- export const apiKeyHeaderName = 'x-api-key';
16
-
17
- export const jobNames = {
18
- pollingExample: 'polling-example',
19
- }
20
-
21
- export const queueNames = {
22
- queueItemExampleQueueName: 'sample-queue-name'
23
- }
24
-
25
- export const triggerBackgroundJob = async (queueName: string, context: BackgroundJobRequestContext, logger: Logger): Promise<void> => {
26
- const queueClient = new QueueClient(process.env.AzureWebJobsStorage as string, queueName);
27
- return triggerBackgroundJobWithQueue(queueClient, context, logger);
28
- }
29
-
30
- const serialiseQueuePayload = (payload: unknown): string => {
31
- const jsonString = JSON.stringify(payload)
32
- return Buffer.from(jsonString).toString('base64')
33
- }
34
-
35
- export const deserialiseQueuePayload = <TPayload>(queueItem: any, logger: Logger): TPayload[] => {
36
- try {
37
- if (typeof queueItem !== 'string') {
38
- if (isArray(queueItem)) {
39
- return queueItem
40
- }
41
- return [queueItem]
42
- }
43
- else {
44
- const jsonString = Buffer.from(queueItem, 'base64').toString()
45
- const parsed = JSON.parse(jsonString);
46
-
47
- if (isArray(parsed)) {
48
- return parsed
49
- }
50
- return [parsed]
51
- }
52
- }
53
- catch (err) {
54
- logger.error('Failed to deserialise queue payload', { ex: winston.exceptions.getAllInfo(err), queueItem });
55
- throw new Error(`Failed to deserialise queue payload`);
56
- }
57
- }
58
-
59
- export const triggerBackgroundJobWithQueue = async (queueClient: QueueClient, context: BackgroundJobRequestContext, logger: Logger): Promise<void> => {
60
- const body = {
61
- ...context
62
- }
63
- const bodyStr = serialiseQueuePayload(body);
64
-
65
- const response = await queueClient.sendMessage(bodyStr, { messageTimeToLive: -1 });
66
-
67
- if (response.errorCode) {
68
- const { requestId, date, errorCode } = response;
69
- logger.error("Failed to trigger background job", { body, requestId, date, errorCode })
70
- throw new Error(`Failed to trigger background job: ${response.errorCode}`);
71
- }
72
- else {
73
- logger.debug("Background job triggered", { body, messageId: response.messageId, context })
74
- }
75
- }
76
-
77
- export const sendQueueMessageToPoisonQueue = async (queueName: string, context: BackgroundJobRequestContext, logger: Logger): Promise<void> => {
78
- const body = {
79
- ...context
80
- }
81
- const bodyStr = serialiseQueuePayload(body);
82
-
83
- // https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-queue-trigger?tabs=python-v2%2Cisolated-process%2Cnodejs-v4%2Cextensionv5&pivots=programming-language-typescript#poison-messages
84
- const queueClient = new QueueClient(process.env.AzureWebJobsStorage as string, `${queueName}-poison`);
85
-
86
- const response = await queueClient.sendMessage(bodyStr, { messageTimeToLive: -1 });
87
-
88
- if (response.errorCode) {
89
- const { requestId, date, errorCode } = response;
90
- logger.error("Failed to push to poison queue", { body, requestId, date, errorCode })
91
- throw new Error(`Failed to push to poison queue: ${response.errorCode}`);
92
- }
93
- else {
94
- logger.verbose("Message pushed to poison queue", { body, messageId: response.messageId, context })
95
- }
1
+ import { QueueClient } from '@azure/storage-queue';
2
+ import { isArray } from 'lodash';
3
+ import type { Logger } from 'winston';
4
+ import winston from 'winston';
5
+
6
+ export interface BackgroundJobRequestContext {
7
+ organisationId?: string;
8
+ organisationBrandId?: string;
9
+ applicationInstallId?: string;
10
+ causationId: string
11
+ correlationId: string
12
+ }
13
+
14
+ export const signatureHeaderName = 'x-signature-hmac';
15
+ export const apiKeyHeaderName = 'x-api-key';
16
+
17
+ export const jobNames = {
18
+ pollingExample: 'polling-example',
19
+ }
20
+
21
+ export const queueNames = {
22
+ queueItemExampleQueueName: 'sample-queue-name'
23
+ }
24
+
25
+ export const triggerBackgroundJob = async (queueName: string, context: BackgroundJobRequestContext, logger: Logger): Promise<void> => {
26
+ const queueClient = new QueueClient(process.env.AzureWebJobsStorage as string, queueName);
27
+ return triggerBackgroundJobWithQueue(queueClient, context, logger);
28
+ }
29
+
30
+ const serialiseQueuePayload = (payload: unknown): string => {
31
+ const jsonString = JSON.stringify(payload)
32
+ return Buffer.from(jsonString).toString('base64')
33
+ }
34
+
35
+ export const deserialiseQueuePayload = <TPayload>(queueItem: any, logger: Logger): TPayload[] => {
36
+ try {
37
+ if (typeof queueItem !== 'string') {
38
+ if (isArray(queueItem)) {
39
+ return queueItem
40
+ }
41
+ return [queueItem]
42
+ }
43
+ else {
44
+ const jsonString = Buffer.from(queueItem, 'base64').toString()
45
+ const parsed = JSON.parse(jsonString);
46
+
47
+ if (isArray(parsed)) {
48
+ return parsed
49
+ }
50
+ return [parsed]
51
+ }
52
+ }
53
+ catch (err) {
54
+ logger.error('Failed to deserialise queue payload', { ex: winston.exceptions.getAllInfo(err), queueItem });
55
+ throw new Error(`Failed to deserialise queue payload`);
56
+ }
57
+ }
58
+
59
+ export const triggerBackgroundJobWithQueue = async (queueClient: QueueClient, context: BackgroundJobRequestContext, logger: Logger): Promise<void> => {
60
+ const body = {
61
+ ...context
62
+ }
63
+ const bodyStr = serialiseQueuePayload(body);
64
+
65
+ const response = await queueClient.sendMessage(bodyStr, { messageTimeToLive: -1 });
66
+
67
+ if (response.errorCode) {
68
+ const { requestId, date, errorCode } = response;
69
+ logger.error("Failed to trigger background job", { body, requestId, date, errorCode })
70
+ throw new Error(`Failed to trigger background job: ${response.errorCode}`);
71
+ }
72
+ else {
73
+ logger.debug("Background job triggered", { body, messageId: response.messageId, context })
74
+ }
75
+ }
76
+
77
+ export const sendQueueMessageToPoisonQueue = async (queueName: string, context: BackgroundJobRequestContext, logger: Logger): Promise<void> => {
78
+ const body = {
79
+ ...context
80
+ }
81
+ const bodyStr = serialiseQueuePayload(body);
82
+
83
+ // https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-queue-trigger?tabs=python-v2%2Cisolated-process%2Cnodejs-v4%2Cextensionv5&pivots=programming-language-typescript#poison-messages
84
+ const queueClient = new QueueClient(process.env.AzureWebJobsStorage as string, `${queueName}-poison`);
85
+
86
+ const response = await queueClient.sendMessage(bodyStr, { messageTimeToLive: -1 });
87
+
88
+ if (response.errorCode) {
89
+ const { requestId, date, errorCode } = response;
90
+ logger.error("Failed to push to poison queue", { body, requestId, date, errorCode })
91
+ throw new Error(`Failed to push to poison queue: ${response.errorCode}`);
92
+ }
93
+ else {
94
+ logger.verbose("Message pushed to poison queue", { body, messageId: response.messageId, context })
95
+ }
96
96
  }
@@ -1,93 +1,93 @@
1
- import * as winston from 'winston';
2
-
3
- import { InvocationContext } from '@azure/functions';
4
- import { SeqTransport } from '@datalust/winston-seq';
5
-
6
- import * as packageJson from '../../../package.json';
7
- import { BackgroundJobRequestContext } from '../jobs';
8
-
9
- import type {
10
- SeekaWebhookPayload, SeekaWebhookPayloadOfSeekaAppWebhookContext
11
- } from '@seeka-labs/sdk-apps-server';
12
-
13
- const loggerTransports: winston.transport[] = [
14
- new winston.transports.Console({
15
- level: process.env.LOGGING_LEVEL,
16
- format: winston.format.combine(
17
- winston.format.errors({ stack: true }),
18
- winston.format.cli(),
19
- winston.format.splat(),
20
- ),
21
- handleExceptions: true,
22
- handleRejections: true,
23
- }),
24
- ]
25
- if (process.env.LOGGING_SEQ_SERVERURL) {
26
- loggerTransports.push(
27
- new SeqTransport({
28
- level: process.env.LOGGING_LEVEL,
29
- serverUrl: process.env.LOGGING_SEQ_SERVERURL,
30
- apiKey: process.env.LOGGING_SEQ_APIKEY,
31
- onError: ((e) => { console.error('Failed to configure Seq logging transport', e) }),
32
- format: winston.format.combine(
33
- winston.format.errors({ stack: true }),
34
- winston.format.json(),
35
- ),
36
- handleExceptions: true,
37
- handleRejections: true,
38
- })
39
- )
40
- }
41
-
42
- export const logger = winston.createLogger({
43
- level: process.env.LOGGING_LEVEL,
44
- defaultMeta: {
45
- seekaAppId: process.env.SEEKA_APP_ID,
46
- Hosting_Provider: 'azure',
47
- Release_Version: `v${packageJson.version}`,
48
- Hosting_Region: process.env.REGION_NAME,
49
- Service_Instance_Id: process.env.WEBSITE_ROLE_INSTANCE_ID,
50
- AzureFunctions_FunctionName: process.env.WEBSITE_SITE_NAME,
51
- Service: `app/${packageJson.name}`,
52
- },
53
- transports: loggerTransports,
54
- exitOnError: false,
55
- });
56
-
57
- export const childLogger = (meta: object) => logger.child(meta);
58
-
59
- export const webhookLogger = (payload: SeekaWebhookPayload, functionContext: InvocationContext) => {
60
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
61
- const meta: any = {
62
- seekaWebhookType: payload.type,
63
- seekaWebhookIsTest: payload.isTest,
64
- RequestId: payload.requestId,
65
- AzureFunctions_InvocationId: functionContext.invocationId,
66
- CausationId: payload.causationId,
67
- CorrelationId: payload.causationId,
68
- }
69
-
70
- const context = (payload as SeekaWebhookPayloadOfSeekaAppWebhookContext).context;
71
- if (context) {
72
- meta.seekaAppInstallId = context.applicationInstallId;
73
- meta.seekaAppInstallOrganisationBrandId = context.organisationBrandId;
74
- meta.seekaAppInstallOrganisationId = context.organisationId;
75
- }
76
-
77
- return childLogger(meta)
78
- }
79
-
80
- export const backgroundJobLogger = (jobName: string, jobContext: BackgroundJobRequestContext | undefined, functionContext: InvocationContext) => {
81
- const meta: object = {
82
- jobContext,
83
- jobName,
84
- AzureFunctions_InvocationId: functionContext.invocationId,
85
- CausationId: jobContext?.causationId,
86
- CorrelationId: jobContext?.causationId,
87
- seekaAppInstallId: jobContext?.applicationInstallId,
88
- seekaAppInstallOrganisationBrandId: jobContext?.organisationBrandId,
89
- seekaAppInstallOrganisationId: jobContext?.organisationId
90
- }
91
-
92
- return childLogger(meta)
1
+ import * as winston from 'winston';
2
+
3
+ import { InvocationContext } from '@azure/functions';
4
+ import { SeqTransport } from '@datalust/winston-seq';
5
+
6
+ import * as packageJson from '../../../package.json';
7
+ import { BackgroundJobRequestContext } from '../jobs';
8
+
9
+ import type {
10
+ SeekaWebhookPayload, SeekaWebhookPayloadOfSeekaAppWebhookContext
11
+ } from '@seeka-labs/sdk-apps-server';
12
+
13
+ const loggerTransports: winston.transport[] = [
14
+ new winston.transports.Console({
15
+ level: process.env.LOGGING_LEVEL,
16
+ format: winston.format.combine(
17
+ winston.format.errors({ stack: true }),
18
+ winston.format.cli(),
19
+ winston.format.splat(),
20
+ ),
21
+ handleExceptions: true,
22
+ handleRejections: true,
23
+ }),
24
+ ]
25
+ if (process.env.LOGGING_SEQ_SERVERURL) {
26
+ loggerTransports.push(
27
+ new SeqTransport({
28
+ level: process.env.LOGGING_LEVEL,
29
+ serverUrl: process.env.LOGGING_SEQ_SERVERURL,
30
+ apiKey: process.env.LOGGING_SEQ_APIKEY,
31
+ onError: ((e) => { console.error('Failed to configure Seq logging transport', e) }),
32
+ format: winston.format.combine(
33
+ winston.format.errors({ stack: true }),
34
+ winston.format.json(),
35
+ ),
36
+ handleExceptions: true,
37
+ handleRejections: true,
38
+ })
39
+ )
40
+ }
41
+
42
+ export const logger = winston.createLogger({
43
+ level: process.env.LOGGING_LEVEL,
44
+ defaultMeta: {
45
+ seekaAppId: process.env.SEEKA_APP_ID,
46
+ Hosting_Provider: 'azure',
47
+ Release_Version: `v${packageJson.version}`,
48
+ Hosting_Region: process.env.REGION_NAME,
49
+ Service_Instance_Id: process.env.WEBSITE_ROLE_INSTANCE_ID,
50
+ AzureFunctions_FunctionName: process.env.WEBSITE_SITE_NAME,
51
+ Service: `app/${packageJson.name}`,
52
+ },
53
+ transports: loggerTransports,
54
+ exitOnError: false,
55
+ });
56
+
57
+ export const childLogger = (meta: object) => logger.child(meta);
58
+
59
+ export const webhookLogger = (payload: SeekaWebhookPayload, functionContext: InvocationContext) => {
60
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
61
+ const meta: any = {
62
+ seekaWebhookType: payload.type,
63
+ seekaWebhookIsTest: payload.isTest,
64
+ RequestId: payload.requestId,
65
+ AzureFunctions_InvocationId: functionContext.invocationId,
66
+ CausationId: payload.causationId,
67
+ CorrelationId: payload.causationId,
68
+ }
69
+
70
+ const context = (payload as SeekaWebhookPayloadOfSeekaAppWebhookContext).context;
71
+ if (context) {
72
+ meta.seekaAppInstallId = context.applicationInstallId;
73
+ meta.seekaAppInstallOrganisationBrandId = context.organisationBrandId;
74
+ meta.seekaAppInstallOrganisationId = context.organisationId;
75
+ }
76
+
77
+ return childLogger(meta)
78
+ }
79
+
80
+ export const backgroundJobLogger = (jobName: string, jobContext: BackgroundJobRequestContext | undefined, functionContext: InvocationContext) => {
81
+ const meta: object = {
82
+ jobContext,
83
+ jobName,
84
+ AzureFunctions_InvocationId: functionContext.invocationId,
85
+ CausationId: jobContext?.causationId,
86
+ CorrelationId: jobContext?.causationId,
87
+ seekaAppInstallId: jobContext?.applicationInstallId,
88
+ seekaAppInstallOrganisationBrandId: jobContext?.organisationBrandId,
89
+ seekaAppInstallOrganisationId: jobContext?.organisationId
90
+ }
91
+
92
+ return childLogger(meta)
93
93
  }
@@ -1,7 +1,7 @@
1
- export interface ISampleAppBrowserSdkPluginConfig {
2
- myAppInstallSetting1: string | number | undefined;
3
- myAppInstallSetting2: string | number | undefined;
4
- appId: string
5
- appInstallId: string
6
- appUrl: string
1
+ export interface ISampleAppBrowserSdkPluginConfig {
2
+ myAppInstallSetting1: string | number | undefined;
3
+ myAppInstallSetting2: string | number | undefined;
4
+ appId: string
5
+ appInstallId: string
6
+ appUrl: string
7
7
  }
@@ -1,41 +1,41 @@
1
- import winston, { Logger } from 'winston';
2
-
3
- import { connect, disconnect, isConnected } from '../state/redis';
4
-
5
- export const startServices = async (logger: Logger) => {
6
- logger.debug(`Trying to connect to Redis - ${process.env.REDIS_CONNECTION_HOST}`)
7
- try {
8
- if (isConnected()) {
9
- logger.verbose(`Redis already connected - ${process.env.REDIS_CONNECTION_HOST}`)
10
- }
11
- else {
12
- logger.profile('service.redis.connect')
13
- await connect();
14
- logger.profile('service.redis.connect')
15
- logger.debug(`Redis connected - ${process.env.REDIS_CONNECTION_HOST}`)
16
- }
17
- }
18
- catch (err) {
19
- logger.error(`Failed to connect to Redis - ${process.env.REDIS_CONNECTION_HOST}`, { ex: winston.exceptions.getAllInfo(err) })
20
- throw err;
21
- }
22
- }
23
-
24
- export const stopServices = async (logger: Logger) => {
25
- logger.debug(`Trying to disconnect from Redis - ${process.env.REDIS_CONNECTION_HOST}`)
26
- try {
27
- if (isConnected() === false) {
28
- logger.verbose(`Redis already disconnected - ${process.env.REDIS_CONNECTION_HOST}`)
29
- }
30
- else {
31
- logger.profile('service.redis.disconnect')
32
- await disconnect();
33
- logger.profile('service.redis.disconnect')
34
- logger.verbose(`Redis disconnected - ${process.env.REDIS_CONNECTION_HOST}`)
35
- }
36
- }
37
- catch (err) {
38
- logger.error(`Failed to disconnect from Redis - ${process.env.REDIS_CONNECTION_HOST}`, { ex: winston.exceptions.getAllInfo(err) })
39
- throw err;
40
- }
1
+ import winston, { Logger } from 'winston';
2
+
3
+ import { connect, disconnect, isConnected } from '../state/redis';
4
+
5
+ export const startServices = async (logger: Logger) => {
6
+ logger.debug(`Trying to connect to Redis - ${process.env.REDIS_CONNECTION_HOST}`)
7
+ try {
8
+ if (isConnected()) {
9
+ logger.verbose(`Redis already connected - ${process.env.REDIS_CONNECTION_HOST}`)
10
+ }
11
+ else {
12
+ logger.profile('service.redis.connect')
13
+ await connect();
14
+ logger.profile('service.redis.connect')
15
+ logger.debug(`Redis connected - ${process.env.REDIS_CONNECTION_HOST}`)
16
+ }
17
+ }
18
+ catch (err) {
19
+ logger.error(`Failed to connect to Redis - ${process.env.REDIS_CONNECTION_HOST}`, { ex: winston.exceptions.getAllInfo(err) })
20
+ throw err;
21
+ }
22
+ }
23
+
24
+ export const stopServices = async (logger: Logger) => {
25
+ logger.debug(`Trying to disconnect from Redis - ${process.env.REDIS_CONNECTION_HOST}`)
26
+ try {
27
+ if (isConnected() === false) {
28
+ logger.verbose(`Redis already disconnected - ${process.env.REDIS_CONNECTION_HOST}`)
29
+ }
30
+ else {
31
+ logger.profile('service.redis.disconnect')
32
+ await disconnect();
33
+ logger.profile('service.redis.disconnect')
34
+ logger.verbose(`Redis disconnected - ${process.env.REDIS_CONNECTION_HOST}`)
35
+ }
36
+ }
37
+ catch (err) {
38
+ logger.error(`Failed to disconnect from Redis - ${process.env.REDIS_CONNECTION_HOST}`, { ex: winston.exceptions.getAllInfo(err) })
39
+ throw err;
40
+ }
41
41
  }
@@ -1,96 +1,96 @@
1
- import { createClient } from 'redis';
2
-
3
- import winston from 'winston';
4
- import { logger } from '../../logging';
5
-
6
- const redisProtocol = process.env.REDIS_CONNECTION_TLS === 'true' ? 'rediss://' : 'redis://';
7
- const redisConn = `${redisProtocol}${process.env.REDIS_CONNECTION_USER}:${process.env.REDIS_CONNECTION_PASSWORD}@${process.env.REDIS_CONNECTION_HOST}:${process.env.REDIS_CONNECTION_PORT}`;
8
-
9
- const redisClient = createClient({
10
- url: redisConn,
11
- disableClientInfo: true,
12
-
13
- })
14
- .on('error', (err) => logger.error('Redis Client ', { ex: winston.exceptions.getAllInfo(err) }));
15
-
16
- export const connect = async () => {
17
- await redisClient.connect();
18
- }
19
-
20
- export const isConnected = () => {
21
- return redisClient.isOpen;
22
- }
23
-
24
- export const disconnect = async () => {
25
- await redisClient.destroy();
26
- }
27
-
28
- const getKeyPrefix = (stateType: string) => `seeka:app:${process.env.SEEKA_APP_ID}:${stateType}`
29
- const getKey = (stateType: string, key: string) => `${getKeyPrefix(stateType)}:${key}`
30
-
31
- export async function getOrCreate<TState>(stateType: string, key: string, toCreate: TState, mode: 'string' | 'json' = 'string'): Promise<TState> {
32
- const fullKey = getKey(stateType, key);
33
- const existingStr = await getString(redisClient, fullKey);
34
- if (existingStr) return JSON.parse(existingStr);
35
-
36
- if (mode === 'json') {
37
- await redisClient.json.set(fullKey, '$', toCreate as never);
38
- }
39
- else {
40
- await redisClient.set(fullKey, JSON.stringify(toCreate));
41
- }
42
-
43
- return toCreate;
44
- }
45
-
46
- export async function tryGet<TState>(stateType: string, key: string, mode: 'string' | 'json' = 'string'): Promise<TState | null> {
47
- const fullKey = getKey(stateType, key);
48
-
49
- if (mode === 'json') {
50
- const existing = await redisClient.json.get(fullKey);
51
- if (existing) return existing as TState;
52
- }
53
- else {
54
- const existingStr = await getString(redisClient, fullKey);
55
- if (existingStr) return JSON.parse(existingStr);
56
- }
57
-
58
- return null;
59
- }
60
-
61
- export async function getList<TState>(stateType: string): Promise<TState[]> {
62
- const prefix = getKeyPrefix(stateType);
63
- const allKeys = await redisClient.keys(`${prefix}:*`);
64
- const listStr = await redisClient.mGet(allKeys);
65
-
66
- if (listStr) return listStr.filter(e => Boolean(e)).map(e => JSON.parse(e as string));
67
-
68
- return [];
69
- }
70
-
71
- export async function set<TState>(stateType: string, key: string, toCreate: TState, mode: 'string' | 'json' = 'string'): Promise<void> {
72
- const fullKey = getKey(stateType, key);
73
-
74
- if (mode === 'json') {
75
- await redisClient.json.set(fullKey, '$', toCreate as never);
76
- }
77
- else {
78
- await redisClient.set(fullKey, JSON.stringify(toCreate));
79
- }
80
- }
81
-
82
- export async function remove(stateType: string, key: string): Promise<void> {
83
- const fullKey = getKey(stateType, key);
84
- await redisClient.del(fullKey);
85
- }
86
-
87
- async function getString(redisClient: any, key: string): Promise<string> {
88
- const result = await redisClient.get(key);
89
- if (typeof result === 'string') {
90
- return result;
91
- }
92
- if (result) {
93
- return result.toString();
94
- }
95
- return '';
96
- }
1
+ import { createClient } from 'redis';
2
+
3
+ import winston from 'winston';
4
+ import { logger } from '../../logging';
5
+
6
+ const redisProtocol = process.env.REDIS_CONNECTION_TLS === 'true' ? 'rediss://' : 'redis://';
7
+ const redisConn = `${redisProtocol}${process.env.REDIS_CONNECTION_USER}:${process.env.REDIS_CONNECTION_PASSWORD}@${process.env.REDIS_CONNECTION_HOST}:${process.env.REDIS_CONNECTION_PORT}`;
8
+
9
+ const redisClient = createClient({
10
+ url: redisConn,
11
+ disableClientInfo: true,
12
+
13
+ })
14
+ .on('error', (err) => logger.error('Redis Client ', { ex: winston.exceptions.getAllInfo(err) }));
15
+
16
+ export const connect = async () => {
17
+ await redisClient.connect();
18
+ }
19
+
20
+ export const isConnected = () => {
21
+ return redisClient.isOpen;
22
+ }
23
+
24
+ export const disconnect = async () => {
25
+ await redisClient.destroy();
26
+ }
27
+
28
+ const getKeyPrefix = (stateType: string) => `seeka:app:${process.env.SEEKA_APP_ID}:${stateType}`
29
+ const getKey = (stateType: string, key: string) => `${getKeyPrefix(stateType)}:${key}`
30
+
31
+ export async function getOrCreate<TState>(stateType: string, key: string, toCreate: TState, mode: 'string' | 'json' = 'string'): Promise<TState> {
32
+ const fullKey = getKey(stateType, key);
33
+ const existingStr = await getString(redisClient, fullKey);
34
+ if (existingStr) return JSON.parse(existingStr);
35
+
36
+ if (mode === 'json') {
37
+ await redisClient.json.set(fullKey, '$', toCreate as never);
38
+ }
39
+ else {
40
+ await redisClient.set(fullKey, JSON.stringify(toCreate));
41
+ }
42
+
43
+ return toCreate;
44
+ }
45
+
46
+ export async function tryGet<TState>(stateType: string, key: string, mode: 'string' | 'json' = 'string'): Promise<TState | null> {
47
+ const fullKey = getKey(stateType, key);
48
+
49
+ if (mode === 'json') {
50
+ const existing = await redisClient.json.get(fullKey);
51
+ if (existing) return existing as TState;
52
+ }
53
+ else {
54
+ const existingStr = await getString(redisClient, fullKey);
55
+ if (existingStr) return JSON.parse(existingStr);
56
+ }
57
+
58
+ return null;
59
+ }
60
+
61
+ export async function getList<TState>(stateType: string): Promise<TState[]> {
62
+ const prefix = getKeyPrefix(stateType);
63
+ const allKeys = await redisClient.keys(`${prefix}:*`);
64
+ const listStr = await redisClient.mGet(allKeys);
65
+
66
+ if (listStr) return listStr.filter(e => Boolean(e)).map(e => JSON.parse(e as string));
67
+
68
+ return [];
69
+ }
70
+
71
+ export async function set<TState>(stateType: string, key: string, toCreate: TState, mode: 'string' | 'json' = 'string'): Promise<void> {
72
+ const fullKey = getKey(stateType, key);
73
+
74
+ if (mode === 'json') {
75
+ await redisClient.json.set(fullKey, '$', toCreate as never);
76
+ }
77
+ else {
78
+ await redisClient.set(fullKey, JSON.stringify(toCreate));
79
+ }
80
+ }
81
+
82
+ export async function remove(stateType: string, key: string): Promise<void> {
83
+ const fullKey = getKey(stateType, key);
84
+ await redisClient.del(fullKey);
85
+ }
86
+
87
+ async function getString(redisClient: any, key: string): Promise<string> {
88
+ const result = await redisClient.get(key);
89
+ if (typeof result === 'string') {
90
+ return result;
91
+ }
92
+ if (result) {
93
+ return result.toString();
94
+ }
95
+ return '';
96
+ }