From fcd2da081fb55f2d2a6936fc79b9486077588408 Mon Sep 17 00:00:00 2001 From: pimp Date: Tue, 23 Jul 2024 15:42:17 +0300 Subject: [PATCH] convert cjs modules to esm --- .../chatMessages/chatMessages.schema.js | 23 +++--- .../chatMessages/endpoints/create.js | 51 +++++++------ .../resources/chatMessages/endpoints/list.js | 48 +++++-------- .../handlers/chatMessageToSockets.js | 12 ++-- .../handlers/updateChildMessagesCount.js | 22 +++--- .../resources/chatRooms/chatRooms.schema.js | 13 ++-- .../chatRooms/handlers/updateLastMessage.js | 29 ++++---- file-upload/app-config/app.js | 28 ++++---- .../resources/files/endpoints/upload.js | 26 +++---- file-upload/resources/files/files.schema.js | 13 ++-- .../files/methods/uploadAndStoreFile.js | 17 ++--- file-upload/services/storageService.js | 35 ++++----- google-oauth/app-config/app.js | 23 +++--- .../resources/auth/endpoints/getGoogleUrl.js | 23 +++--- .../resources/auth/endpoints/googleSignIn.js | 46 +++++------- google-oauth/services/base64.js | 27 +++---- google-oauth/services/googleAuth.js | 32 ++++----- stripe-subscriptions/app-config/app.js | 27 +++---- .../resources/stripe/endpoints/cancel.js | 28 +++----- .../stripe/endpoints/onSubscribed.js | 71 +++++++------------ .../resources/stripe/endpoints/reactivate.js | 30 +++----- .../resources/stripe/endpoints/subscribe.js | 70 ++++++------------ .../resources/stripe/stripe.schema.js | 7 +- .../resources/users/users.extends.schema.js | 9 +-- stripe-subscriptions/services/stripe.js | 10 +-- 25 files changed, 298 insertions(+), 422 deletions(-) diff --git a/chat-messaging/resources/chatMessages/chatMessages.schema.js b/chat-messaging/resources/chatMessages/chatMessages.schema.js index bbbf825..69d96d7 100644 --- a/chat-messaging/resources/chatMessages/chatMessages.schema.js +++ b/chat-messaging/resources/chatMessages/chatMessages.schema.js @@ -1,33 +1,28 @@ -const Joi = require('joi'); - -module.exports = Joi.object({ +import Joi from "joi"; +export default Joi.object({ _id: Joi.string(), - id: Joi.string().allow(null).allow(''), + id: Joi.string().allow(null).allow(""), createdOn: Joi.date(), updatedOn: Joi.date(), - attachments: Joi.array() .items( Joi.object({ - url: Joi.string().allow(null).allow(''), - }) + url: Joi.string().allow(null).allow(""), + }), ) .allow(null), - messageHTML: Joi.string().allow(null).allow(''), - + messageHTML: Joi.string().allow(null).allow(""), chatRoom: Joi.object({ _id: Joi.string(), }).allow(null), fromUser: Joi.object({ _id: Joi.string(), - avatarUrl: Joi.string().allow(null).allow(''), - fullName: Joi.string().allow(null).allow(''), + avatarUrl: Joi.string().allow(null).allow(""), + fullName: Joi.string().allow(null).allow(""), }).allow(null), - metadata: Joi.object({}).allow(null), - parentMessage: Joi.object({ _id: Joi.string(), }).allow(null), childMessagesCount: Joi.number(), -}); \ No newline at end of file +}); diff --git a/chat-messaging/resources/chatMessages/endpoints/create.js b/chat-messaging/resources/chatMessages/endpoints/create.js index fec3835..ebfe779 100644 --- a/chat-messaging/resources/chatMessages/endpoints/create.js +++ b/chat-messaging/resources/chatMessages/endpoints/create.js @@ -1,49 +1,46 @@ -const Joi = require('joi'); - -const chatMessageService = require('db').services.chatMessages; - -module.exports.handler = async (ctx) => { - const { messageHTML, attachments, chatRoomId, id, parentMessageId } = ctx.validatedData; - +import Joi from "joi"; +import db from "db"; +import attachUser from "middlewares/attachUser"; +import shouldExist from "middlewares/shouldExist"; +const chatMessageService = db.services.chatMessages; +export const handler = async (ctx) => { + const { messageHTML, attachments, chatRoomId, id, parentMessageId } = + ctx.validatedData; const chatMessage = await chatMessageService.create({ id, chatRoom: { _id: chatRoomId }, fromUser: { _id: ctx.state.user._id }, messageHTML, attachments, - ...(parentMessageId ? { parentMessage: { _id: parentMessageId }} : { }) + ...(parentMessageId ? { parentMessage: { _id: parentMessageId } } : {}), }); - ctx.body = chatMessage; }; - -module.exports.middlewares = [ - require('middlewares/attachUser'), - require('middlewares/shouldExist')('chatRooms', { +export const middlewares = [ + attachUser, + shouldExist("chatRooms", { criteria: (ctx) => { return { _id: ctx.request.body.chatRoomId, - 'users._id': ctx.state.user._id + "users._id": ctx.state.user._id, }; }, }), ]; - -module.exports.endpoint = { - url: '/', - method: 'post', +export const endpoint = { + url: "/", + method: "post", }; - -module.exports.requestSchema = Joi.object({ +export const requestSchema = Joi.object({ attachments: Joi.array() .items( Joi.object({ - url: Joi.string().allow(null).allow(''), - }) + url: Joi.string().allow(null).allow(""), + }), ) .allow(null), - messageHTML: Joi.string().allow(null).allow(''), - chatRoomId: Joi.string().allow(null).allow(''), - id: Joi.string().allow(null).allow(''), - parentMessageId: Joi.string().allow(null).allow(''), -}); \ No newline at end of file + messageHTML: Joi.string().allow(null).allow(""), + chatRoomId: Joi.string().allow(null).allow(""), + id: Joi.string().allow(null).allow(""), + parentMessageId: Joi.string().allow(null).allow(""), +}); diff --git a/chat-messaging/resources/chatMessages/endpoints/list.js b/chat-messaging/resources/chatMessages/endpoints/list.js index 36e78f8..3688373 100644 --- a/chat-messaging/resources/chatMessages/endpoints/list.js +++ b/chat-messaging/resources/chatMessages/endpoints/list.js @@ -1,22 +1,20 @@ -const Joi = require('joi'); - -const chatMessageService = require('db').services.chatMessages; -const chatRoomService = require('db').services.chatRooms; - -module.exports.handler = async (ctx) => { +import Joi from "joi"; +import db from "db"; +import isAuthorized from "middlewares/isAuthorized"; +const chatMessageService = db.services.chatMessages; +const chatRoomService = db.services.chatRooms; +export const handler = async (ctx) => { const { page, perPage, - sort = '-createdOn', + sort = "-createdOn", beforeDate, chatRoomId, } = ctx.validatedData; - let chatRoom = await chatRoomService.findOne({ _id: ctx.request.query.chatRoomId, - 'users._id': ctx.state.user._id, + "users._id": ctx.state.user._id, }); - if (!chatRoom) { ctx.body = { isNoChatRoom: true, @@ -26,33 +24,25 @@ module.exports.handler = async (ctx) => { }; return; } - const { results, pagesCount, count } = await chatMessageService.find( { ...(beforeDate ? { createdOn: { $lte: beforeDate } } : {}), - - 'chatRoom._id': chatRoomId, + "chatRoom._id": chatRoomId, }, - { page, perPage, sort } + { page, perPage, sort }, ); - ctx.body = { results, pagesCount, count }; }; - -module.exports.middlewares = [ - require('middlewares/isAuthorized'), -]; - -module.exports.endpoint = { - url: '/', - method: 'get', +export const middlewares = [isAuthorized]; +export const endpoint = { + url: "/", + method: "get", }; - -module.exports.requestSchema = Joi.object({ +export const requestSchema = Joi.object({ page: Joi.number(), perPage: Joi.number(), - sort: Joi.string().allow(null).allow(''), - afterDate: Joi.string().allow(null).allow(''), + sort: Joi.string().allow(null).allow(""), + afterDate: Joi.string().allow(null).allow(""), beforeDate: Joi.date(), - chatRoomId: Joi.string().allow(null).allow(''), -}); \ No newline at end of file + chatRoomId: Joi.string().allow(null).allow(""), +}); diff --git a/chat-messaging/resources/chatMessages/handlers/chatMessageToSockets.js b/chat-messaging/resources/chatMessages/handlers/chatMessageToSockets.js index 0692b5b..0656499 100644 --- a/chat-messaging/resources/chatMessages/handlers/chatMessageToSockets.js +++ b/chat-messaging/resources/chatMessages/handlers/chatMessageToSockets.js @@ -1,10 +1,10 @@ -const ioEmitter = require('ioEmitter'); -const chatMessageService = require('db').services.chatMessages; - -chatMessageService.on('created', async ({ doc: chatMessage }) => { +import ioEmitter from "ioEmitter"; +import db from "db"; +const chatMessageService = db.services.chatMessages; +chatMessageService.on("created", async ({ doc: chatMessage }) => { ioEmitter .to(`chatRoom-${chatMessage.chatRoom._id}`) - .emit('chatMessage:created', { + .emit("chatMessage:created", { chatMessage, }); -}); \ No newline at end of file +}); diff --git a/chat-messaging/resources/chatMessages/handlers/updateChildMessagesCount.js b/chat-messaging/resources/chatMessages/handlers/updateChildMessagesCount.js index 42d1a6d..eb5f00e 100644 --- a/chat-messaging/resources/chatMessages/handlers/updateChildMessagesCount.js +++ b/chat-messaging/resources/chatMessages/handlers/updateChildMessagesCount.js @@ -1,16 +1,18 @@ -const chatMessageService = require('db').services.chatMessages; - +import db from "db"; +const chatMessageService = db.services.chatMessages; let updateChildMessagesCount = async ({ doc: chatMessage }) => { if (chatMessage.parentMessage) { await chatMessageService.atomic.update( - { _id: chatMessage.parentMessage._id }, { + { _id: chatMessage.parentMessage._id }, + { $set: { - childMessagesCount: await chatMessageService.count({'parentMessage._id': chatMessage.parentMessage._id}) - } - } + childMessagesCount: await chatMessageService.count({ + "parentMessage._id": chatMessage.parentMessage._id, + }), + }, + }, ); } -} - -chatMessageService.on('created', updateChildMessagesCount); -chatMessageService.on('removed', updateChildMessagesCount); \ No newline at end of file +}; +chatMessageService.on("created", updateChildMessagesCount); +chatMessageService.on("removed", updateChildMessagesCount); diff --git a/chat-messaging/resources/chatRooms/chatRooms.schema.js b/chat-messaging/resources/chatRooms/chatRooms.schema.js index 7b44128..46d70c3 100644 --- a/chat-messaging/resources/chatRooms/chatRooms.schema.js +++ b/chat-messaging/resources/chatRooms/chatRooms.schema.js @@ -1,21 +1,18 @@ -const Joi = require('joi'); - -module.exports = Joi.object({ +import Joi from "joi"; +export default Joi.object({ _id: Joi.string(), createdOn: Joi.date(), updatedOn: Joi.date(), - users: Joi.array() .items( Joi.object({ _id: Joi.string(), - }).allow(null) + }).allow(null), ) .allow(null), - - lastMessageHTML: Joi.string().allow(null).allow(''), + lastMessageHTML: Joi.string().allow(null).allow(""), lastMessageUser: Joi.object({ _id: Joi.string(), }).allow(null), lastMessageSentOn: Joi.date(), -}); \ No newline at end of file +}); diff --git a/chat-messaging/resources/chatRooms/handlers/updateLastMessage.js b/chat-messaging/resources/chatRooms/handlers/updateLastMessage.js index ba1d53e..24a04f3 100644 --- a/chat-messaging/resources/chatRooms/handlers/updateLastMessage.js +++ b/chat-messaging/resources/chatRooms/handlers/updateLastMessage.js @@ -1,16 +1,13 @@ -const chatMessageService = require('db').services.chatMessages; -const chatRoomService = require('db').services.chatRooms; - -chatMessageService.on('created', async ({ doc: message }) => { - await chatRoomService.updateOne( - { _id: message.chatRoom._id }, - (chatRoom) => { - return { - ...chatRoom, - lastMessageHTML: message.messageHTML, - lastMessageUser: message.fromUser || null, - lastMessageSentOn: message.createdOn, - }; - } - ); -}); \ No newline at end of file +import db from "db"; +const chatMessageService = db.services.chatMessages; +const chatRoomService = db.services.chatRooms; +chatMessageService.on("created", async ({ doc: message }) => { + await chatRoomService.updateOne({ _id: message.chatRoom._id }, (chatRoom) => { + return { + ...chatRoom, + lastMessageHTML: message.messageHTML, + lastMessageUser: message.fromUser || null, + lastMessageSentOn: message.createdOn, + }; + }); +}); diff --git a/file-upload/app-config/app.js b/file-upload/app-config/app.js index f4575de..e99a941 100644 --- a/file-upload/app-config/app.js +++ b/file-upload/app-config/app.js @@ -1,12 +1,16 @@ -const assertEnv = require('app-config/assertEnv'); - -assertEnv(['STORAGE_ENDPOINT', 'STORAGE_ACCESS_KEY', 'STORAGE_SECRET_ACCESS_KEY', 'STORAGE_BUCKET']); - -module.exports = { - cloudStorage: { - endpoint: process.env.STORAGE_ENDPOINT, - accessKeyId: process.env.STORAGE_ACCESS_KEY, - secretAccessKey: process.env.STORAGE_SECRET_ACCESS_KEY, - bucket: process.env.STORAGE_BUCKET, - }, -}; \ No newline at end of file +import assertEnv from "app-config/assertEnv"; +assertEnv([ + "STORAGE_ENDPOINT", + "STORAGE_ACCESS_KEY", + "STORAGE_SECRET_ACCESS_KEY", + "STORAGE_BUCKET", +]); +export const cloudStorage = { + endpoint: process.env.STORAGE_ENDPOINT, + accessKeyId: process.env.STORAGE_ACCESS_KEY, + secretAccessKey: process.env.STORAGE_SECRET_ACCESS_KEY, + bucket: process.env.STORAGE_BUCKET, +}; +export default { + cloudStorage, +}; diff --git a/file-upload/resources/files/endpoints/upload.js b/file-upload/resources/files/endpoints/upload.js index ee71355..e76caa6 100644 --- a/file-upload/resources/files/endpoints/upload.js +++ b/file-upload/resources/files/endpoints/upload.js @@ -1,11 +1,8 @@ -const Joi = require('joi'); - -const isAuthorized = require('middlewares/isAuthorized'); -const uploadFile = require('middlewares/uploadFile'); - -const uploadAndStoreFile = require('resources/files/methods/uploadAndStoreFile'); - -module.exports.handler = async (ctx) => { +import Joi from "joi"; +import isAuthorized from "middlewares/isAuthorized"; +import uploadFile from "middlewares/uploadFile"; +import uploadAndStoreFile from "resources/files/methods/uploadAndStoreFile"; +export const handler = async (ctx) => { const { file } = ctx.request; let createdFile = await uploadAndStoreFile({ file, @@ -13,12 +10,9 @@ module.exports.handler = async (ctx) => { }); ctx.body = createdFile; }; - -module.exports.middlewares = [isAuthorized, uploadFile.single('file')]; - -module.exports.endpoint = { - url: '/', - method: 'post', +export const middlewares = [isAuthorized, uploadFile.single("file")]; +export const endpoint = { + url: "/", + method: "post", }; - -module.exports.requestSchema = Joi.object({}); \ No newline at end of file +export const requestSchema = Joi.object({}); diff --git a/file-upload/resources/files/files.schema.js b/file-upload/resources/files/files.schema.js index c232d24..32c56af 100644 --- a/file-upload/resources/files/files.schema.js +++ b/file-upload/resources/files/files.schema.js @@ -1,17 +1,16 @@ -const Joi = require('joi'); - -module.exports = Joi.object({ +import Joi from "joi"; +export default Joi.object({ _id: Joi.string(), createdOn: Joi.date(), updatedOn: Joi.date(), - name: Joi.string().allow(null).allow(''), - url: Joi.string().allow(null).allow(''), + name: Joi.string().allow(null).allow(""), + url: Joi.string().allow(null).allow(""), size: Joi.object({}).allow(null), - customerId: Joi.string().allow(null).allow(''), + customerId: Joi.string().allow(null).allow(""), creator: Joi.object({ _id: Joi.string(), }).allow(null), customer: Joi.object({ _id: Joi.string(), }).allow(null), -}); \ No newline at end of file +}); diff --git a/file-upload/resources/files/methods/uploadAndStoreFile.js b/file-upload/resources/files/methods/uploadAndStoreFile.js index ab2381f..e0a0dc5 100644 --- a/file-upload/resources/files/methods/uploadAndStoreFile.js +++ b/file-upload/resources/files/methods/uploadAndStoreFile.js @@ -1,20 +1,17 @@ -const fileService = require('db').services.files; -const cloudStorageService = require('services/storageService'); - -module.exports = async ({ file, userId, customerId }) => { +import db from "db"; +import cloudStorageService from "services/storageService"; +const fileService = db.services.files; +export default async ({ file, userId, customerId }) => { const fileName = `${Date.now()}-${file.originalname}`; - const data = await cloudStorageService.uploadPublic( `stream/${customerId || userId}/${fileName}`, - file + file, ); - let { Location:url } = data; - + let { Location: url } = data; const createdFile = await fileService.create({ creator: { _id: userId }, name: file.originalname, url, }); - return createdFile; -}; \ No newline at end of file +}; diff --git a/file-upload/services/storageService.js b/file-upload/services/storageService.js index 5598393..3696adc 100644 --- a/file-upload/services/storageService.js +++ b/file-upload/services/storageService.js @@ -1,74 +1,65 @@ -const AWS = require('aws-sdk'); -const config = require('app-config'); - -config.assert('cloudStorage'); - +import AWS from "aws-sdk"; +import config from "app-config"; +config.assert("cloudStorage"); const Bucket = config.cloudStorage.bucket; const spacesEndpoint = new AWS.Endpoint(config.cloudStorage.endpoint); - const storage = new AWS.S3({ endpoint: spacesEndpoint, accessKeyId: config.cloudStorage.accessKeyId, secretAccessKey: config.cloudStorage.secretAccessKey, }); - function getSignedUrl(fileName) { const params = { Bucket, Key: fileName, Expires: 1800, }; - - return storage.getSignedUrl('getObject', params); + return storage.getSignedUrl("getObject", params); } - function upload(filePath, file) { const params = { Bucket, ContentType: file.mimetype, Body: file.buffer, Key: filePath, - ACL: 'private', + ACL: "private", }; - return storage.upload(params).promise(); } - function uploadPublic(filePath, file) { const params = { Bucket, ContentType: file.mimetype, Body: file.buffer, Key: filePath, - ACL: 'public-read', + ACL: "public-read", }; - return storage.upload(params).promise(); } - function copy(filePath, copyFilePath) { const params = { Bucket, CopySource: `${Bucket}/${copyFilePath}`, Key: filePath, }; - return storage.copyObject(params).promise(); } - function remove(filePath) { const params = { Bucket, Key: filePath, }; - return storage.deleteObject(params).promise(); } - -module.exports = { +export { getSignedUrl }; +export { copy }; +export { upload }; +export { uploadPublic }; +export { remove }; +export default { getSignedUrl, copy, upload, uploadPublic, remove, -}; \ No newline at end of file +}; diff --git a/google-oauth/app-config/app.js b/google-oauth/app-config/app.js index 0bfa4ef..8dbbdf3 100644 --- a/google-oauth/app-config/app.js +++ b/google-oauth/app-config/app.js @@ -1,12 +1,11 @@ -const config = require('app-config'); -const assertEnv = require('app-config/assertEnv'); - -assertEnv(['GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET']); - -module.exports = { - google: { - clientId: process.env.GOOGLE_CLIENT_ID, - clientSecret: process.env.GOOGLE_CLIENT_SECRET, - redirectUri: `${config.domain}/auth/google/sign-in`, - }, -}; \ No newline at end of file +import config from "app-config"; +import assertEnv from "app-config/assertEnv"; +assertEnv(["GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET"]); +export const google = { + clientId: process.env.GOOGLE_CLIENT_ID, + clientSecret: process.env.GOOGLE_CLIENT_SECRET, + redirectUri: `${config.domain}/auth/google/sign-in`, +}; +export default { + google, +}; diff --git a/google-oauth/resources/auth/endpoints/getGoogleUrl.js b/google-oauth/resources/auth/endpoints/getGoogleUrl.js index dea9303..1ca2c86 100644 --- a/google-oauth/resources/auth/endpoints/getGoogleUrl.js +++ b/google-oauth/resources/auth/endpoints/getGoogleUrl.js @@ -1,11 +1,8 @@ -const Joi = require('joi'); - -const googleAuth = require('services/googleAuth'); - -module.exports.handler = async (ctx) => { - if (ctx.get('Content-Type') === 'application/json') { +import Joi from "joi"; +import googleAuth from "services/googleAuth"; +export const handler = async (ctx) => { + if (ctx.get("Content-Type") === "application/json") { ctx.status = 302; - ctx.body = { url: googleAuth.oAuthURL({ url: ctx.request.query.redirect_to }), }; @@ -13,14 +10,12 @@ module.exports.handler = async (ctx) => { ctx.redirect( googleAuth.oAuthURL({ url: ctx.request.query.redirect_to, - }) + }), ); } }; - -module.exports.endpoint = { - url: '/google/url', - method: 'get', +export const endpoint = { + url: "/google/url", + method: "get", }; - -module.exports.requestSchema = Joi.object({}); \ No newline at end of file +export const requestSchema = Joi.object({}); diff --git a/google-oauth/resources/auth/endpoints/googleSignIn.js b/google-oauth/resources/auth/endpoints/googleSignIn.js index 65d232e..6fba569 100644 --- a/google-oauth/resources/auth/endpoints/googleSignIn.js +++ b/google-oauth/resources/auth/endpoints/googleSignIn.js @@ -1,51 +1,39 @@ -const Joi = require('joi'); - -const config = require('app-config'); - -const ensureUserCreated = require('resources/users/methods/ensureUserCreated'); -const storeToken = require('resources/tokens/methods/storeToken'); - -const googleAuth = require('services/googleAuth'); -const { decode } = require('services/base64'); - -module.exports.handler = async (ctx) => { +import Joi from "joi"; +import config from "app-config"; +import ensureUserCreated from "resources/users/methods/ensureUserCreated"; +import storeToken from "resources/tokens/methods/storeToken"; +import googleAuth from "services/googleAuth"; +import base64 from "services/base64"; +const { decode } = base64; +export const handler = async (ctx) => { const { code } = ctx.validatedData; - const { isValid, payload: googleAuthPayload } = await googleAuth.exchangeCodeForToken(code); - ctx.assert(isValid, 404); - let state = decode(ctx.request.query.state); - const { _id: userId } = await ensureUserCreated({ - fullName: `${googleAuthPayload.given_name} ${googleAuthPayload.family_name || ''}`, + fullName: `${googleAuthPayload.given_name} ${googleAuthPayload.family_name || ""}`, email: googleAuthPayload.email, avatarUrl: googleAuthPayload.picture, - oauth: { google: { clientId: googleAuthPayload.sub, }, }, }); - const { otp } = await storeToken(ctx, { userId }); - if (state?.url) ctx.redirect( (state?.url || config.webUrl) + - (state?.url && state?.url.includes('?') ? '&' : '?') + - 'otp=' + - otp + (state?.url && state?.url.includes("?") ? "&" : "?") + + "otp=" + + otp, ); }; - -module.exports.endpoint = { - url: '/google/sign-in', - method: 'get', +export const endpoint = { + url: "/google/sign-in", + method: "get", }; - -module.exports.requestSchema = Joi.object({ +export const requestSchema = Joi.object({ code: Joi.string().required(), -}); \ No newline at end of file +}); diff --git a/google-oauth/services/base64.js b/google-oauth/services/base64.js index 2f0ae5b..5c835b2 100644 --- a/google-oauth/services/base64.js +++ b/google-oauth/services/base64.js @@ -1,12 +1,15 @@ -module.exports = { - encode: (obj) => Buffer.from(JSON.stringify(obj)).toString('base64'), - decode: (str) => { - let decodedStr = Buffer.from(str, 'base64').toString(); - try { - let obj = JSON.parse(decodedStr); - return obj; - } catch (err) { - return decodedStr; - } - }, -}; \ No newline at end of file +export const encode = (obj) => + Buffer.from(JSON.stringify(obj)).toString("base64"); +export const decode = (str) => { + let decodedStr = Buffer.from(str, "base64").toString(); + try { + let obj = JSON.parse(decodedStr); + return obj; + } catch (err) { + return decodedStr; + } +}; +export default { + encode, + decode, +}; diff --git a/google-oauth/services/googleAuth.js b/google-oauth/services/googleAuth.js index e2d5816..e660b46 100644 --- a/google-oauth/services/googleAuth.js +++ b/google-oauth/services/googleAuth.js @@ -1,44 +1,38 @@ -const { OAuth2Client } = require('google-auth-library'); - -const config = require('app-config'); -const logger = require('logger'); -const { encode } = require('services/base64'); - -config.assert('google'); - +import googleAuthLibrary from "google-auth-library"; +import config from "app-config"; +import logger from "logger"; +import base64 from "services/base64"; +const { OAuth2Client } = googleAuthLibrary; +const { encode } = base64; +config.assert("google"); const client = new OAuth2Client( config.google.clientId, config.google.clientSecret, - config.google.redirectUri + config.google.redirectUri, ); - -module.exports.oAuthURL = ({ url, fingerprint }) => +export const oAuthURL = ({ url, fingerprint }) => client.generateAuthUrl({ - access_type: 'offline', - scope: ['email', 'profile'], + access_type: "offline", + scope: ["email", "profile"], include_granted_scopes: true, state: encode({ url, fingerprint }), }); - -module.exports.exchangeCodeForToken = async (code) => { +export const exchangeCodeForToken = async (code) => { try { const { tokens } = await client.getToken(code); - const ticket = await client.verifyIdToken({ idToken: tokens.id_token, audience: config.google.clientId, }); - return { isValid: true, payload: ticket.getPayload(), }; } catch ({ message, ...rest }) { logger.error(`Exchange code for token error: ${message}`); - return { isValid: false, payload: { message }, }; } -}; \ No newline at end of file +}; diff --git a/stripe-subscriptions/app-config/app.js b/stripe-subscriptions/app-config/app.js index 3658929..ba57e86 100644 --- a/stripe-subscriptions/app-config/app.js +++ b/stripe-subscriptions/app-config/app.js @@ -1,16 +1,11 @@ -const assertEnv = require('app-config/assertEnv'); - -// assertEnv(['STRIPE_SECRET', 'STRIPE_WEBHOOK_SECRET', 'STRIPE_PRICES']); - -module.exports = { - stripe: { - secretKey: process.env.STRIPE_SECRET, - - webhookSecret: - process.env.STRIPE_WEBHOOK_SECRET, - - plans: (process.env.STRIPE_PRICES || '').split(',').map(priceId => ({ - priceId - })), - } -}; \ No newline at end of file +import assertEnv from "app-config/assertEnv"; +export const stripe = { + secretKey: process.env.STRIPE_SECRET, + webhookSecret: process.env.STRIPE_WEBHOOK_SECRET, + plans: (process.env.STRIPE_PRICES || "").split(",").map((priceId) => ({ + priceId, + })), +}; +export default { + stripe, +}; diff --git a/stripe-subscriptions/resources/stripe/endpoints/cancel.js b/stripe-subscriptions/resources/stripe/endpoints/cancel.js index 8c6cf93..f501cc3 100644 --- a/stripe-subscriptions/resources/stripe/endpoints/cancel.js +++ b/stripe-subscriptions/resources/stripe/endpoints/cancel.js @@ -1,30 +1,22 @@ -const Joi = require('joi'); - -const stripe = require('services/stripe'); - -module.exports.handler = async (ctx) => { +import Joi from "joi"; +import stripe from "services/stripe"; +import isAuthorized from "middlewares/isAuthorized"; +export const handler = async (ctx) => { if (ctx.state.user.subscription) { const subscription = await stripe.subscriptions.update( ctx.state.user.subscription.id, { cancel_at_period_end: true, - } + }, ); - ctx.body = { isCancelled: true, subscription }; } else { ctx.body = { isCancelled: true }; } }; - -module.exports.middlewares = [ - require('middlewares/isAuthorized'), -]; - -module.exports.endpoint = { - url: '/cancel', - method: 'post', +export const middlewares = [isAuthorized]; +export const endpoint = { + url: "/cancel", + method: "post", }; - -module.exports.requestSchema = Joi.object({ -}); \ No newline at end of file +export const requestSchema = Joi.object({}); diff --git a/stripe-subscriptions/resources/stripe/endpoints/onSubscribed.js b/stripe-subscriptions/resources/stripe/endpoints/onSubscribed.js index 8802ab6..44022db 100644 --- a/stripe-subscriptions/resources/stripe/endpoints/onSubscribed.js +++ b/stripe-subscriptions/resources/stripe/endpoints/onSubscribed.js @@ -1,34 +1,26 @@ -const Joi = require('joi'); - -const config = require('app-config'); - -const stripe = require('services/stripe'); - -const stripeService = require('db').services.stripe; - -let userService = require('db').services.users; - -module.exports.handler = async (ctx) => { - const sig = ctx.headers['stripe-signature']; - +import Joi from "joi"; +import config from "app-config"; +import stripe from "services/stripe"; +import db from "db"; +const stripeService = db.services.stripe; +let userService = db.services.users; +export const handler = async (ctx) => { + const sig = ctx.headers["stripe-signature"]; let event; - try { event = stripe.webhooks.constructEvent( ctx.request.rawBody, sig, - config.stripe.webhookSecret + config.stripe.webhookSecret, ); } catch (err) { - console.log('webhook error', err.message); + console.log("webhook error", err.message); ctx.status = 400; ctx.body = { msg: `Webhook Error: ${err.message}` }; return; } - - if (event.type === 'customer.subscription.created') { + if (event.type === "customer.subscription.created") { let priceId = event.data.object.items.data[0].price.id; - await userService.atomic.update( { _id: event.data.object.metadata.userId }, { @@ -39,41 +31,36 @@ module.exports.handler = async (ctx) => { activatedOn: new Date(), }, }, - } + }, ); - } else if (event.type === 'customer.subscription.updated') { + } else if (event.type === "customer.subscription.updated") { let priceId = event.data.object.items.data[0].price.id; - let updateQuery = { - 'subscription.status': event.data.object.status, - 'subscription.priceId': priceId, + "subscription.status": event.data.object.status, + "subscription.priceId": priceId, }; - if (event.data.object.cancel_at_period_end) { - updateQuery['subscription.cancelledOn'] = new Date(); + updateQuery["subscription.cancelledOn"] = new Date(); } else { - updateQuery['subscription.cancelledOn'] = null; + updateQuery["subscription.cancelledOn"] = null; } - await userService.atomic.update( - { 'subscription.id': event.data.object.id }, + { "subscription.id": event.data.object.id }, { $set: updateQuery, - } + }, ); - } else if (event.type === 'customer.subscription.deleted') { + } else if (event.type === "customer.subscription.deleted") { await userService.atomic.update( - { 'subscription.id': event.data.object.id }, + { "subscription.id": event.data.object.id }, { $set: { - 'subscription.isStopped': true, + "subscription.isStopped": true, }, - } + }, ); } - stripeService.create(event.data.object); - // // Handle the event // switch (event.type) { // case 'charge.captured': @@ -88,16 +75,12 @@ module.exports.handler = async (ctx) => { // default: // console.log(`Unhandled event type ${event.type}`); // } - // const { } = ctx.validatedData; // const results = stripeService.find({ }); ctx.body = {}; }; - -module.exports.endpoint = { - url: '/on-subscribed', - method: 'post', +export const endpoint = { + url: "/on-subscribed", + method: "post", }; - -module.exports.requestSchema = Joi.object({ -}); \ No newline at end of file +export const requestSchema = Joi.object({}); diff --git a/stripe-subscriptions/resources/stripe/endpoints/reactivate.js b/stripe-subscriptions/resources/stripe/endpoints/reactivate.js index 4d1bef6..c3e8363 100644 --- a/stripe-subscriptions/resources/stripe/endpoints/reactivate.js +++ b/stripe-subscriptions/resources/stripe/endpoints/reactivate.js @@ -1,31 +1,23 @@ -const Joi = require('joi'); - -const config = require('app-config'); - -const stripe = require('services/stripe'); - -module.exports.handler = async (ctx) => { +import Joi from "joi"; +import config from "app-config"; +import stripe from "services/stripe"; +import isAuthorized from "middlewares/isAuthorized"; +export const handler = async (ctx) => { if (ctx.state.user.subscription) { const subscription = await stripe.subscriptions.update( ctx.state.user.subscription.id, { cancel_at_period_end: false, - } + }, ); - ctx.body = { isReactivated: true, subscription }; } else { ctx.body = { isReactivated: true }; } }; - -module.exports.middlewares = [ - require('middlewares/isAuthorized'), -]; - -module.exports.endpoint = { - url: '/reactivate', - method: 'post', +export const middlewares = [isAuthorized]; +export const endpoint = { + url: "/reactivate", + method: "post", }; - -module.exports.requestSchema = Joi.object({}); \ No newline at end of file +export const requestSchema = Joi.object({}); diff --git a/stripe-subscriptions/resources/stripe/endpoints/subscribe.js b/stripe-subscriptions/resources/stripe/endpoints/subscribe.js index 5f970b3..5215a58 100644 --- a/stripe-subscriptions/resources/stripe/endpoints/subscribe.js +++ b/stripe-subscriptions/resources/stripe/endpoints/subscribe.js @@ -1,74 +1,59 @@ -const Joi = require('joi'); - -const userService = require('db').services.users; - -const config = require('app-config'); - -const stripe = require('services/stripe'); - +import Joi from "joi"; +import db from "db"; +import config from "app-config"; +import stripe from "services/stripe"; +import isAuthorized from "middlewares/isAuthorized"; +const userService = db.services.users; let createCheckoutSession = async (ctx, { priceId }) => { const session = await stripe.checkout.sessions.create({ customer: ctx.state.user.stripe.id, - line_items: [ { price: priceId, quantity: 1, }, ], - customer_update: { - address: 'auto', + address: "auto", }, - - mode: 'subscription', + mode: "subscription", success_url: config.stripe.successURl, metadata: { userId: ctx.state.user._id }, }); - return session; }; - -module.exports.handler = async (ctx) => { +export const handler = async (ctx) => { let { priceId = config.stripe.plans[0].priceId } = ctx.validatedData; - if (!ctx.state.user.stripe) { let stripeCustomer = await stripe.customers.create({ name: ctx.state.user.fullName, email: ctx.state.user.email, }); - await userService.atomic.update( { _id: ctx.state.user._id }, - { $set: { stripe: { id: stripeCustomer.id } } } + { $set: { stripe: { id: stripeCustomer.id } } }, ); - ctx.state.user.stripe = stripeCustomer; } - if (ctx.state.user.subscription && !ctx.state.user.subscription.isStopped) { const currentSubscription = await stripe.subscriptions.retrieve( - ctx.state.user.subscription.id + ctx.state.user.subscription.id, ); - let itemId = currentSubscription.items.data[0].id; - const subscription = await stripe.subscriptions.update( currentSubscription.id, { - proration_behavior: 'always_invoice', + proration_behavior: "always_invoice", items: [ { id: itemId, price: priceId, }, ], - } + }, ); - return (ctx.body = { isUpgraded: true, subscription }); } - let { data: customerPaymentMethods } = await stripe.customers.listPaymentMethods(ctx.state.user.stripe.id, { limit: 1, @@ -77,8 +62,8 @@ module.exports.handler = async (ctx) => { try { const subscription = await stripe.subscriptions.create({ customer: ctx.state.user.stripe.id, - collection_method: 'charge_automatically', - payment_behavior: 'error_if_incomplete', + collection_method: "charge_automatically", + payment_behavior: "error_if_incomplete", default_payment_method: customerPaymentMethods[0].id, items: [ { @@ -87,7 +72,6 @@ module.exports.handler = async (ctx) => { ], metadata: { userId: ctx.state.user._id }, }); - userService.atomic.update( { _id: ctx.state.user._id }, { @@ -98,32 +82,24 @@ module.exports.handler = async (ctx) => { activatedOn: new Date(), }, }, - } + }, ); - ctx.body = { isUpgraded: true, subscription }; } catch (err) { - console.log('stripe err', err); + console.log("stripe err", err); let session = await createCheckoutSession(ctx, { priceId }); - return (ctx.body = { url: session.url }); } } else { let session = await createCheckoutSession(ctx, { priceId }); - ctx.body = { url: session.url }; } }; - -module.exports.middlewares = [ - require('middlewares/isAuthorized'), -]; - -module.exports.endpoint = { - url: '/subscribe', - method: 'get', +export const middlewares = [isAuthorized]; +export const endpoint = { + url: "/subscribe", + method: "get", }; - -module.exports.requestSchema = Joi.object({ +export const requestSchema = Joi.object({ priceId: Joi.string(), -}); \ No newline at end of file +}); diff --git a/stripe-subscriptions/resources/stripe/stripe.schema.js b/stripe-subscriptions/resources/stripe/stripe.schema.js index fe578e5..a5972ff 100644 --- a/stripe-subscriptions/resources/stripe/stripe.schema.js +++ b/stripe-subscriptions/resources/stripe/stripe.schema.js @@ -1,7 +1,6 @@ -const Joi = require('joi'); - -module.exports = Joi.object({ +import Joi from "joi"; +export default Joi.object({ _id: Joi.string(), createdOn: Joi.date(), updatedOn: Joi.date(), -}); \ No newline at end of file +}); diff --git a/stripe-subscriptions/resources/users/users.extends.schema.js b/stripe-subscriptions/resources/users/users.extends.schema.js index a5e90e3..646c3e4 100644 --- a/stripe-subscriptions/resources/users/users.extends.schema.js +++ b/stripe-subscriptions/resources/users/users.extends.schema.js @@ -1,5 +1,4 @@ -const Joi = require("joi"); - +import Joi from "joi"; const users = { subscription: Joi.object({ id: Joi.string(), @@ -8,10 +7,8 @@ const users = { cancelledOn: Joi.date(), isStopped: Joi.boolean(), }), - stripe: Joi.object({ - id: Joi.string(), + id: Joi.string(), }), }; - -module.exports = users; +export default users; diff --git a/stripe-subscriptions/services/stripe.js b/stripe-subscriptions/services/stripe.js index 129adf3..0d1ca72 100644 --- a/stripe-subscriptions/services/stripe.js +++ b/stripe-subscriptions/services/stripe.js @@ -1,7 +1,7 @@ -const config = require('app-config'); +import config from "app-config"; +import stripe$0 from "stripe"; -config.assert('stripe'); +config.assert("stripe"); +const stripe = stripe$0(config.stripe.secretKey); -const stripe = require('stripe')(config.stripe.secretKey); - -module.exports = stripe; \ No newline at end of file +export default stripe;