@unchainedshop/plugins 1.1.5 → 1.2.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 (89) hide show
  1. package/jest.config.js +5 -0
  2. package/lib/files/gridfs/gridfs-adapter.js +1 -1
  3. package/lib/files/gridfs/gridfs-adapter.js.map +1 -1
  4. package/lib/files/gridfs/gridfs-webhook.d.ts +2 -1
  5. package/lib/files/gridfs/gridfs-webhook.js +5 -4
  6. package/lib/files/gridfs/gridfs-webhook.js.map +1 -1
  7. package/lib/files/gridfs/index.d.ts +3 -3
  8. package/lib/files/gridfs/index.js.map +1 -1
  9. package/lib/files/gridfs/promisePipe.d.ts +1 -1
  10. package/lib/files/gridfs/promisePipe.js.map +1 -1
  11. package/lib/files/gridfs/sign.d.ts +1 -1
  12. package/lib/files/gridfs/sign.js.map +1 -1
  13. package/lib/files/minio/minio-adapter.js +1 -1
  14. package/lib/files/minio/minio-adapter.js.map +1 -1
  15. package/lib/files/minio/minio-webhook.d.ts +2 -1
  16. package/lib/files/minio/minio-webhook.js +30 -28
  17. package/lib/files/minio/minio-webhook.js.map +1 -1
  18. package/lib/payment/apple-iap/adapter.d.ts +2 -1
  19. package/lib/payment/apple-iap/adapter.js +94 -92
  20. package/lib/payment/apple-iap/adapter.js.map +1 -1
  21. package/lib/payment/apple-iap/index.d.ts +2 -1
  22. package/lib/payment/apple-iap/index.js +2 -1
  23. package/lib/payment/apple-iap/index.js.map +1 -1
  24. package/lib/payment/bity/adapter.d.ts +2 -1
  25. package/lib/payment/bity/adapter.js +50 -48
  26. package/lib/payment/bity/adapter.js.map +1 -1
  27. package/lib/payment/bity/index.d.ts +2 -1
  28. package/lib/payment/bity/index.js +2 -1
  29. package/lib/payment/bity/index.js.map +1 -1
  30. package/lib/payment/braintree.js +2 -2
  31. package/lib/payment/braintree.js.map +1 -1
  32. package/lib/payment/cryptopay.d.ts +2 -1
  33. package/lib/payment/cryptopay.js +60 -58
  34. package/lib/payment/cryptopay.js.map +1 -1
  35. package/lib/payment/datatrans-v2/index.d.ts +2 -1
  36. package/lib/payment/datatrans-v2/index.js +2 -1
  37. package/lib/payment/datatrans-v2/index.js.map +1 -1
  38. package/lib/payment/datatrans-v2/middleware.d.ts +2 -1
  39. package/lib/payment/datatrans-v2/middleware.js +99 -97
  40. package/lib/payment/datatrans-v2/middleware.js.map +1 -1
  41. package/lib/payment/paypal-checkout.js +1 -1
  42. package/lib/payment/paypal-checkout.js.map +1 -1
  43. package/lib/payment/postfinance-checkout/index.d.ts +2 -1
  44. package/lib/payment/postfinance-checkout/index.js +2 -1
  45. package/lib/payment/postfinance-checkout/index.js.map +1 -1
  46. package/lib/payment/postfinance-checkout/middleware.d.ts +2 -1
  47. package/lib/payment/postfinance-checkout/middleware.js +36 -34
  48. package/lib/payment/postfinance-checkout/middleware.js.map +1 -1
  49. package/lib/payment/stripe.d.ts +2 -1
  50. package/lib/payment/stripe.js +63 -60
  51. package/lib/payment/stripe.js.map +1 -1
  52. package/lib/payment/worldline-saferpay/worldline-saferpay-client/index.d.ts +3 -3
  53. package/lib/pricing/product-price-ECB-interbank-exchange.js +1 -1
  54. package/lib/pricing/product-price-ECB-interbank-exchange.js.map +1 -1
  55. package/lib/pricing/product-price-cryptopay.d.ts +2 -1
  56. package/lib/pricing/product-price-cryptopay.js +20 -18
  57. package/lib/pricing/product-price-cryptopay.js.map +1 -1
  58. package/lib/worker/ZombieKillerWorker.js.map +1 -1
  59. package/lib/worker/email.js +1 -0
  60. package/lib/worker/email.js.map +1 -1
  61. package/package.json +30 -24
  62. package/src/files/gridfs/gridfs-adapter.ts +1 -1
  63. package/src/files/gridfs/gridfs-webhook.ts +62 -0
  64. package/src/files/gridfs/{index.js → index.ts} +0 -0
  65. package/src/files/gridfs/{promisePipe.js → promisePipe.ts} +0 -0
  66. package/src/files/gridfs/{sign.js → sign.ts} +0 -0
  67. package/src/files/minio/minio-adapter.ts +1 -1
  68. package/src/files/minio/minio-webhook.js +33 -30
  69. package/src/payment/apple-iap/adapter.ts +113 -110
  70. package/src/payment/apple-iap/index.ts +2 -1
  71. package/src/payment/bity/adapter.ts +53 -51
  72. package/src/payment/bity/index.ts +2 -1
  73. package/src/payment/braintree.ts +2 -2
  74. package/src/payment/cryptopay.ts +69 -67
  75. package/src/payment/datatrans-v2/index.ts +3 -1
  76. package/src/payment/datatrans-v2/middleware.ts +129 -123
  77. package/src/payment/paypal-checkout.ts +1 -1
  78. package/src/payment/postfinance-checkout/index.ts +3 -1
  79. package/src/payment/postfinance-checkout/middleware.ts +42 -40
  80. package/src/payment/stripe.ts +82 -74
  81. package/src/payment/worldline-saferpay/worldline-saferpay-client/index.ts +3 -3
  82. package/src/pricing/product-discount.ts +1 -1
  83. package/src/pricing/product-price-ECB-interbank-exchange.ts +1 -1
  84. package/src/pricing/product-price-cryptopay.ts +20 -18
  85. package/src/worker/ZombieKillerWorker.ts +5 -5
  86. package/src/worker/email.ts +1 -0
  87. package/tsconfig.json +26 -5
  88. package/src/files/gridfs/gridfs-webhook.js +0 -60
  89. package/tsconfig.build.json +0 -26
@@ -5,50 +5,52 @@ import { createLogger } from '@unchainedshop/logger';
5
5
  import { WebhookData } from './types';
6
6
  import { getTransaction, getTransactionCompletion } from './api';
7
7
 
8
- const { PFCHECKOUT_WEBHOOK_PATH = '/graphql/postfinance-checkout' } = process.env;
8
+ const { PFCHECKOUT_WEBHOOK_PATH = '/payment/postfinance-checkout' } = process.env;
9
9
 
10
10
  const logger = createLogger('unchained:core-payment:postfinance-checkout');
11
11
 
12
- useMiddlewareWithCurrentContext(PFCHECKOUT_WEBHOOK_PATH, bodyParser.json());
12
+ export default (app) => {
13
+ useMiddlewareWithCurrentContext(app, PFCHECKOUT_WEBHOOK_PATH, bodyParser.json());
13
14
 
14
- useMiddlewareWithCurrentContext(PFCHECKOUT_WEBHOOK_PATH, async (req, res) => {
15
- const context = req.unchainedContext as Context;
16
- const data = req.body as WebhookData;
17
- if (data.listenerEntityTechnicalName === 'TransactionCompletion') {
18
- try {
19
- const transactionCompletion = await getTransactionCompletion(data.entityId as unknown as string);
20
- const transaction = await getTransaction(
21
- transactionCompletion.linkedTransaction as unknown as string,
22
- );
23
- const { orderPaymentId } = transaction.metaData as { orderPaymentId: string };
24
- const orderPayment = await context.modules.orders.payments.findOrderPayment({
25
- orderPaymentId,
26
- });
27
- if (!orderPayment) throw new Error('Order Payment not found');
28
- const order = await context.modules.orders.checkout(
29
- orderPayment.orderId,
30
- {
31
- paymentContext: {
32
- transactionId: transactionCompletion.linkedTransaction,
15
+ useMiddlewareWithCurrentContext(app, PFCHECKOUT_WEBHOOK_PATH, async (req, res) => {
16
+ const context = req.unchainedContext as Context;
17
+ const data = req.body as WebhookData;
18
+ if (data.listenerEntityTechnicalName === 'TransactionCompletion') {
19
+ try {
20
+ const transactionCompletion = await getTransactionCompletion(data.entityId as unknown as string);
21
+ const transaction = await getTransaction(
22
+ transactionCompletion.linkedTransaction as unknown as string,
23
+ );
24
+ const { orderPaymentId } = transaction.metaData as { orderPaymentId: string };
25
+ const orderPayment = await context.modules.orders.payments.findOrderPayment({
26
+ orderPaymentId,
27
+ });
28
+ if (!orderPayment) throw new Error('Order Payment not found');
29
+ const order = await context.modules.orders.checkout(
30
+ orderPayment.orderId,
31
+ {
32
+ paymentContext: {
33
+ transactionId: transactionCompletion.linkedTransaction,
34
+ },
33
35
  },
34
- },
35
- context,
36
- );
37
- logger.info(
38
- `PostFinance Checkout Webhook: Transaction ${transactionCompletion.linkedTransaction} marked order payment ID ${transaction.metaData.orderPaymentId} as paid`,
36
+ context,
37
+ );
38
+ logger.info(
39
+ `PostFinance Checkout Webhook: Transaction ${transactionCompletion.linkedTransaction} marked order payment ID ${transaction.metaData.orderPaymentId} as paid`,
40
+ );
41
+ res.writeHead(200);
42
+ res.end(`Order marked as paid: ${order.orderNumber}`);
43
+ } catch (e) {
44
+ logger.error(`PostFinance Checkout Webhook: Unchained rejected to checkout with message`, e);
45
+ res.writeHead(500);
46
+ res.end(JSON.stringify(e));
47
+ }
48
+ } else {
49
+ logger.error(
50
+ `PostFinance Checkout Webhook: Received unknown listenerEntityTechnicalName ${data.listenerEntityTechnicalName}`,
39
51
  );
40
- res.writeHead(200);
41
- res.end(`Order marked as paid: ${order.orderNumber}`);
42
- } catch (e) {
43
- logger.error(`PostFinance Checkout Webhook: Unchained rejected to checkout with message`, e);
44
- res.writeHead(500);
45
- res.end(JSON.stringify(e));
52
+ res.writeHead(404);
53
+ res.end();
46
54
  }
47
- } else {
48
- logger.error(
49
- `PostFinance Checkout Webhook: Received unknown listenerEntityTechnicalName ${data.listenerEntityTechnicalName}`,
50
- );
51
- res.writeHead(404);
52
- res.end();
53
- }
54
- });
55
+ });
56
+ };
@@ -5,100 +5,108 @@ import { useMiddlewareWithCurrentContext } from '@unchainedshop/api';
5
5
  import { PaymentAdapter, PaymentDirector, PaymentError } from '@unchainedshop/core-payment';
6
6
  import { createLogger } from '@unchainedshop/logger';
7
7
 
8
- const logger = createLogger('unchained:core-payment:stripe');
9
-
10
- const {
11
- STRIPE_SECRET,
12
- STRIPE_ENDPOINT_SECRET,
13
- EMAIL_WEBSITE_NAME,
14
- STRIPE_WEBHOOK_PATH = '/graphql/stripe',
15
- } = process.env;
16
-
17
8
  /*
18
9
  Test Webhooks:
19
10
 
20
11
  brew install stripe/stripe-cli/stripe
21
12
  stripe login --api-key sk_....
22
- stripe listen --forward-to http://localhost:3000/graphql/stripe
13
+ stripe listen --forward-to http://localhost:3000/payment/stripe
23
14
  stripe trigger payment_intent.succeeded
24
15
  */
25
16
 
26
- const stripe = require('stripe')(STRIPE_SECRET); // eslint-disable-line
17
+ import createStripeClient from 'stripe';
18
+
19
+ const logger = createLogger('unchained:core-payment:stripe');
20
+
21
+ const {
22
+ STRIPE_SECRET,
23
+ STRIPE_ENDPOINT_SECRET,
24
+ EMAIL_WEBSITE_NAME,
25
+ STRIPE_WEBHOOK_PATH = '/payment/stripe',
26
+ } = process.env;
27
+
28
+ const stripe = createStripeClient(STRIPE_SECRET);
27
29
 
28
- useMiddlewareWithCurrentContext(STRIPE_WEBHOOK_PATH, bodyParser.raw({ type: 'application/json' }));
30
+ export default (app) => {
31
+ useMiddlewareWithCurrentContext(
32
+ app,
33
+ STRIPE_WEBHOOK_PATH,
34
+ bodyParser.raw({ type: 'application/json' }),
35
+ );
29
36
 
30
- useMiddlewareWithCurrentContext(STRIPE_WEBHOOK_PATH, async (request, response) => {
31
- const sig = request.headers['stripe-signature'];
32
- const resolvedContext = request.unchainedContext as Context;
33
- const { modules, services } = resolvedContext;
37
+ useMiddlewareWithCurrentContext(app, STRIPE_WEBHOOK_PATH, async (request, response) => {
38
+ const sig = request.headers['stripe-signature'];
39
+ const resolvedContext = request.unchainedContext as Context;
40
+ const { modules, services } = resolvedContext;
34
41
 
35
- let event;
42
+ let event;
36
43
 
37
- try {
38
- event = stripe.webhooks.constructEvent(request.body, sig, STRIPE_ENDPOINT_SECRET);
39
- } catch (err) {
40
- response.writeHead(400);
41
- response.end(`Webhook Error: ${err.message}`);
42
- return;
43
- }
44
+ try {
45
+ event = stripe.webhooks.constructEvent(request.body, sig, STRIPE_ENDPOINT_SECRET);
46
+ } catch (err) {
47
+ response.writeHead(400);
48
+ response.end(`Webhook Error: ${err.message}`);
49
+ return;
50
+ }
44
51
 
45
- try {
46
- if (event.type === 'payment_intent.succeeded') {
47
- const paymentIntent = event.data.object;
48
- const orderPaymentId = paymentIntent.metadata?.orderPaymentId;
52
+ try {
53
+ if (event.type === 'payment_intent.succeeded') {
54
+ const paymentIntent = event.data.object;
55
+ const orderPaymentId = paymentIntent.metadata?.orderPaymentId;
49
56
 
50
- await modules.orders.payments.logEvent(orderPaymentId, event, resolvedContext.userId);
57
+ await modules.orders.payments.logEvent(orderPaymentId, event, resolvedContext.userId);
51
58
 
52
- const orderPayment = await modules.orders.payments.findOrderPayment({
53
- orderPaymentId,
54
- });
59
+ const orderPayment = await modules.orders.payments.findOrderPayment({
60
+ orderPaymentId,
61
+ });
55
62
 
56
- const order = await modules.orders.checkout(
57
- orderPayment.orderId,
58
- {
59
- transactionContext: {
60
- paymentIntentId: paymentIntent.id,
63
+ const order = await modules.orders.checkout(
64
+ orderPayment.orderId,
65
+ {
66
+ transactionContext: {
67
+ paymentIntentId: paymentIntent.id,
68
+ },
69
+ paymentContext: {
70
+ paymentIntentId: paymentIntent.id,
71
+ },
61
72
  },
62
- paymentContext: {
63
- paymentIntentId: paymentIntent.id,
64
- },
65
- },
66
- resolvedContext,
67
- );
68
-
69
- logger.info(`Stripe Webhook: Unchained confirmed checkout for order ${order.orderNumber}`, {
70
- orderId: order._id,
71
- });
72
- } else if (event.type === 'setup_intent.succeeded') {
73
- const setupIntent = event.data.object;
74
- const { paymentProviderId, userId } = setupIntent.metadata;
75
-
76
- await services.payment.registerPaymentCredentials(
77
- paymentProviderId,
78
- {
79
- transactionContext: {
80
- setupIntentId: setupIntent.id,
73
+ resolvedContext,
74
+ );
75
+
76
+ logger.info(`Stripe Webhook: Unchained confirmed checkout for order ${order.orderNumber}`, {
77
+ orderId: order._id,
78
+ });
79
+ } else if (event.type === 'setup_intent.succeeded') {
80
+ const setupIntent = event.data.object;
81
+ const { paymentProviderId, userId } = setupIntent.metadata;
82
+
83
+ await services.payment.registerPaymentCredentials(
84
+ paymentProviderId,
85
+ {
86
+ transactionContext: {
87
+ setupIntentId: setupIntent.id,
88
+ },
81
89
  },
82
- },
83
- resolvedContext,
84
- );
85
-
86
- logger.info(`Stripe Webhook: Unchained registered payment credentials for ${userId}`, {
87
- userId,
88
- });
89
- } else {
90
- response.writeHead(404);
91
- response.end();
90
+ resolvedContext,
91
+ );
92
+
93
+ logger.info(`Stripe Webhook: Unchained registered payment credentials for ${userId}`, {
94
+ userId,
95
+ });
96
+ } else {
97
+ response.writeHead(404);
98
+ response.end();
99
+ return;
100
+ }
101
+ } catch (err) {
102
+ response.writeHead(400);
103
+ response.end(`Webhook Error: ${err.message}`);
92
104
  return;
93
105
  }
94
- } catch (err) {
95
- response.writeHead(400);
96
- response.end(`Webhook Error: ${err.message}`);
97
- return;
98
- }
99
- // Return a 200 response to acknowledge receipt of the event
100
- response.end(JSON.stringify({ received: true }));
101
- });
106
+ // Return a 200 response to acknowledge receipt of the event
107
+ response.end(JSON.stringify({ received: true }));
108
+ });
109
+ };
102
110
 
103
111
  const createRegistrationIntent = async ({ userId, name, email, paymentProviderId }, options = {}) => {
104
112
  const customer = await stripe.customers.create({
@@ -1,8 +1,8 @@
1
1
  export { SaferpayClient } from './api/SaferpayClient';
2
2
 
3
- export {
3
+ export type {
4
4
  PaymentPageInitializeInput,
5
5
  PaymentPageInitializeResponse,
6
6
  } from './models/PaymentPageInitialize';
7
- export { PaymentPageAssertInput, PaymentPageAssertResponse } from './models/PaymentPageAssert';
8
- export { TransactionCancelInput, TransactionCancelResponse } from './models/TransactionCancel';
7
+ export type { PaymentPageAssertInput, PaymentPageAssertResponse } from './models/PaymentPageAssert';
8
+ export type { TransactionCancelInput, TransactionCancelResponse } from './models/TransactionCancel';
@@ -1,4 +1,4 @@
1
- import { Discount, DiscountConfiguration } from '@unchainedshop/types/discount';
1
+ import type { Discount, DiscountConfiguration } from '@unchainedshop/types/discount';
2
2
  import {
3
3
  IProductPricingAdapter,
4
4
  ProductPricingRowCategory,
@@ -1,6 +1,7 @@
1
1
  import { IProductPricingAdapter } from '@unchainedshop/types/products.pricing';
2
2
  import fetch from 'isomorphic-unfetch';
3
3
  import { ProductPricingDirector, ProductPricingAdapter } from '@unchainedshop/core-products';
4
+ import xmlJs from 'xml-js';
4
5
 
5
6
  import Cache from './utils/cache';
6
7
 
@@ -42,7 +43,6 @@ const SUPPORTED_CURRENCIES = [
42
43
  ];
43
44
 
44
45
  const cache = new Cache(CACHE_PERIOD);
45
- const xmlJs = require('xml-js'); // eslint-disable-line
46
46
 
47
47
  const getEURexchangeRateForCurrency = async (currency) => {
48
48
  const response = cache.get(currency, () =>
@@ -3,23 +3,25 @@ import { ProductPriceRate } from '@unchainedshop/types/products.pricing';
3
3
  import bodyParser from 'body-parser';
4
4
  import { useMiddlewareWithCurrentContext } from '@unchainedshop/api';
5
5
 
6
- const { CRYPTOPAY_SECRET, CRYPTOPAY_PRICING_WEBHOOK_PATH = '/graphql/cryptopay-pricing' } = process.env;
6
+ const { CRYPTOPAY_SECRET, CRYPTOPAY_PRICING_WEBHOOK_PATH = '/payment/cryptopay-pricing' } = process.env;
7
7
 
8
- useMiddlewareWithCurrentContext(CRYPTOPAY_PRICING_WEBHOOK_PATH, bodyParser.json());
8
+ export default (app) => {
9
+ useMiddlewareWithCurrentContext(app, CRYPTOPAY_PRICING_WEBHOOK_PATH, bodyParser.json());
9
10
 
10
- useMiddlewareWithCurrentContext(CRYPTOPAY_PRICING_WEBHOOK_PATH, async (request, response) => {
11
- const resolvedContext = request.unchainedContext as Context;
12
- const { baseCurrency, token, rate, timestamp, secret } = request.body;
13
- if (secret !== CRYPTOPAY_SECRET) {
14
- response.end(JSON.stringify({ success: false }));
15
- return;
16
- }
17
- const rateData: ProductPriceRate = {
18
- baseCurrency,
19
- quoteCurrency: token,
20
- rate,
21
- timestamp,
22
- };
23
- const success = await resolvedContext.modules.products.prices.rates.updateRate(rateData);
24
- response.end(JSON.stringify({ success }));
25
- });
11
+ useMiddlewareWithCurrentContext(app, CRYPTOPAY_PRICING_WEBHOOK_PATH, async (request, response) => {
12
+ const resolvedContext = request.unchainedContext as Context;
13
+ const { baseCurrency, token, rate, timestamp, secret } = request.body;
14
+ if (secret !== CRYPTOPAY_SECRET) {
15
+ response.end(JSON.stringify({ success: false }));
16
+ return;
17
+ }
18
+ const rateData: ProductPriceRate = {
19
+ baseCurrency,
20
+ quoteCurrency: token,
21
+ rate,
22
+ timestamp,
23
+ };
24
+ const success = await resolvedContext.modules.products.prices.rates.updateRate(rateData);
25
+ response.end(JSON.stringify({ success }));
26
+ });
27
+ };
@@ -70,11 +70,11 @@ export const ZombieKillerWorker: IWorkerAdapter<
70
70
  const deletedFilesCount =
71
71
  fileIdsToRemove.length > 0
72
72
  ? await services.files.removeFiles(
73
- {
74
- fileIds: fileIdsToRemove,
75
- },
76
- unchainedAPI,
77
- )
73
+ {
74
+ fileIds: fileIdsToRemove,
75
+ },
76
+ unchainedAPI,
77
+ )
78
78
  : 0;
79
79
 
80
80
  // Return delete count
@@ -5,6 +5,7 @@ import fs from 'fs';
5
5
  import path from 'path';
6
6
  import os from 'os';
7
7
  import open from 'open';
8
+ import nodemailer from 'nodemailer';
8
9
 
9
10
  const logger = createLogger('unchained:plugins:worker:email');
10
11
 
package/tsconfig.json CHANGED
@@ -1,8 +1,29 @@
1
1
  {
2
- "extends": "./tsconfig.build.json",
3
2
  "compilerOptions": {
4
- "noEmit": true,
5
- "types": ["node"]
3
+ "allowJs": true,
4
+ "allowSyntheticDefaultImports": true,
5
+ "declaration": true,
6
+ "esModuleInterop": true,
7
+ "experimentalDecorators": true,
8
+ "forceConsistentCasingInFileNames": true,
9
+ "lib": [
10
+ "esnext"
11
+ ],
12
+ "module": "esnext",
13
+ "moduleResolution": "node",
14
+ "noImplicitReturns": true,
15
+ "noUnusedLocals": false,
16
+ "outDir": "lib",
17
+ "preserveWatchOutput": true,
18
+ "skipLibCheck": true,
19
+ "sourceMap": true,
20
+ "target": "esnext",
21
+ "types": [
22
+ "node",
23
+ "jest"
24
+ ]
6
25
  },
7
- "include": ["src"]
8
- }
26
+ "include": [
27
+ "src"
28
+ ]
29
+ }
@@ -1,60 +0,0 @@
1
- import { useMiddlewareWithCurrentContext } from '@unchainedshop/api';
2
- import { log, LogLevel } from '@unchainedshop/logger';
3
- import sign from './sign';
4
- import promisePipe from './promisePipe';
5
- import buildHashedFilename from '@unchainedshop/file-upload/lib/buildHashedFilename';
6
-
7
- const { ROOT_URL } = process.env;
8
-
9
- /*
10
- curl -vvv -X PUT -T /Users/pozylon/Downloads/grafik.png http://localhost:4010/gridfs/user-avatars/hans.png?e=1653059591506&s=df8626a1c9b9006249d7f1928fd530579fed57216f1bdcb83c28a8322cdc90b1
11
- */
12
-
13
- useMiddlewareWithCurrentContext('/gridfs', async (req, res) => {
14
- try {
15
- const { services, modules } = req.unchainedContext;
16
- const url = new URL(req.url, ROOT_URL);
17
- const [, directoryName, fileName] = url.pathname.split('/');
18
-
19
- if (req.method === 'PUT') {
20
- const { s: signature, e: expiryTimestamp } = req.query;
21
- const expiryDate = new Date(parseInt(expiryTimestamp, 10));
22
- const fileId = buildHashedFilename(directoryName, fileName, expiryDate);
23
- if (sign(directoryName, fileId, expiryDate.getTime()) === signature) {
24
- const file = await modules.files.findFile({ fileId });
25
- if (file.expires === null) {
26
- res.writeHead(503);
27
- res.end('File already linked');
28
- }
29
- const writeStream = await modules.gridfsFileUploads.createWriteStream(
30
- directoryName,
31
- fileId,
32
- fileName,
33
- );
34
- const { length } = await promisePipe(req, writeStream);
35
- await services.files.linkFile({ fileId, size: length }, req.unchainedContext);
36
- res.writeHead(200);
37
- res.end();
38
- return;
39
- }
40
- res.writeHead(403);
41
- res.end();
42
- return;
43
- }
44
- if (req.method === 'GET') {
45
- const fileId = fileName;
46
- const readStream = await modules.gridfsFileUploads.createReadStream(directoryName, fileId);
47
- await promisePipe(readStream, res);
48
- res.writeHead(200);
49
- res.end();
50
- return;
51
- }
52
- res.writeHead(404);
53
- res.end();
54
- return;
55
- } catch (e) {
56
- log(e.message, { level: LogLevel.Error });
57
- res.writeHead(503);
58
- res.end(JSON.stringify(e));
59
- }
60
- });
@@ -1,26 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "allowJs": true,
4
- "allowSyntheticDefaultImports": true,
5
- "declaration": true,
6
- "esModuleInterop": true,
7
- "experimentalDecorators": true,
8
- "forceConsistentCasingInFileNames": true,
9
- "lib": ["esnext"],
10
- "module": "esnext",
11
- "moduleResolution": "node",
12
- "noImplicitReturns": true,
13
- "noUnusedLocals": false,
14
- "outDir": "lib",
15
- "preserveWatchOutput": true,
16
- "skipLibCheck": true,
17
- "sourceMap": true,
18
- "target": "esnext",
19
- "types": ["node"],
20
- "baseUrl": ".", // This must be specified if "paths" is.
21
- "paths": {
22
- "meteor/unchained:*": ["node_modules/@unchainedshop/types/index.d.ts"]
23
- }
24
- },
25
- "include": ["src"]
26
- }