Skip to content

Commit

Permalink
Merge pull request #8 from devreluije/master
Browse files Browse the repository at this point in the history
New environment system (using fs-recursive@1.1.7)
  • Loading branch information
LeadcodeDev committed Aug 20, 2021
2 parents c155b61 + 451de75 commit a53e2d5
Show file tree
Hide file tree
Showing 5 changed files with 105 additions and 113 deletions.
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,11 @@
"typescript": "^4.2.3"
},
"dependencies": {
"@discord-factory/env": "^0.0.0",
"@types/mock-fs": "^4.13.0",
"cross-env": "^7.0.3",
"discord.js": "^13.0.1",
"dotenv": "^10.0.0",
"fs-recursive": "1.1.4",
"fs-recursive": "1.1.7",
"js-yaml": "^4.1.0",
"mock-fs": "^4.14.0",
"module-alias": "^2.2.2",
Expand Down
133 changes: 60 additions & 73 deletions src/managers/EnvironmentManager.ts
Original file line number Diff line number Diff line change
@@ -1,106 +1,93 @@
import YAML from 'js-yaml'
import { config } from 'dotenv'
import { fetch } from 'fs-recursive'
import { EnvironmentFactory } from '../types/Factory'
import { fetchSortedExpression, File } from 'fs-recursive'
import {
EnvironmentFactory,
Environment,
EnvironmentElement,
} from 'types/Factory'

config()

export default class EnvironmentManager {
public $env: EnvironmentFactory = {
public $env: Environment = {
type: '',
path: '',
content: '',
content: {},
}

public async load () {
const environment = await fetch(process.cwd(),
['env', 'json', 'yaml', 'yml'],
'utf-8',
['node_modules'])

const environments = Array.from(environment.entries())
.filter(([_, file]) => file.filename === 'environment' || file.extension === 'env')
.map(([_, file]) => file)

const env = environments.find(file => file.extension === 'env')
if (env) {
return this.$env = {
type: env.extension,
path: env.path,
content: '',
}
}
public async load() {
const environment = await fetchSortedExpression(
process.cwd(),
/^environment\.(json|yml|yaml)|\.env$/,
['env', 'json', 'yml', 'yaml'],
'utf-8',
['node_modules']
)

const json = environments.find(file => file.extension === 'json')
if (json) {
const content = await json.getContent('utf-8')
return this.$env = {
type: json.extension,
path: json.path,
content: content!.toString(),
}
}
if (!environment.length)
throw new Error('Environment file is missing, please create one.')

const yaml = environments.find(file => file.extension === 'yaml' || file.extension === 'yml')
if (yaml) {
const content = await yaml.getContent('utf-8')
return this.$env = {
type: yaml.extension,
path: yaml.path,
content: content!.toString(),
}
const types: EnvironmentFactory = {
env: this.getFromEnv,
json: this.getFromJSON,
yml: this.getFromYAML,
yaml: this.getFromYAML,
}
const file = environment[0]
const factory = types[file.extension]

throw new Error('Environment file is missing, please create one.')
}
if (!factory) throw new Error(`Factory not found for file: ${file.path}`)

public get (key: string) {
const environments = {
env: () => this.getFromEnv(key),
json: () => this.getFromJSON(key),
yaml: () => this.getFromYAML(key),
yml: () => this.getFromYAML(key),
}
return environments[this.$env.type]()
return (this.$env = {
type: file.extension,
path: file.path,
content: await factory(file),
})
}

private filterEnvironment (identifier) {
private filterEnvironment(identifier: string) {
return Object.entries(process.env)
.map(([key, value]) => key.toLowerCase().startsWith(identifier) ? { [key.replace(`${identifier.toUpperCase()}_`, '')]: value } : null)
.filter(rule => rule).reduce((acc, t) => ({ ...acc, ...t }))
.filter(([key]) => key.toLowerCase().startsWith(identifier))
.map(([key, value]) => ({
[key.replace(`${identifier.toUpperCase()}_`, '')]: value!,
}))
.reduce((acc, t) => ({ ...acc, ...t }))
}

private getFromEnv (key: string) {
private async getFromEnv(_file: File): Promise<EnvironmentElement> {
const messages = this.filterEnvironment('message')
const presets = this.filterEnvironment('preset')
const partials = Object.entries(process.env)
.flatMap(([key, value]: any) => {
return key.toLowerCase().startsWith('partial') ? { [key]: value } : null
})
.filter(preset => preset)
.flatMap((preset: any) => {
return Object.entries(preset).flatMap((item) => {
return item[1] === 'true' && item[0].replace('PARTIAL_', '')
}).filter(item => item)
}) as Array<string>
const partials = Object.keys(
Object.entries(process.env)
.filter(([key]) => key.toLowerCase().startsWith('partial'))
.filter(([_, value]) => value === 'true')
.map(([key, value]) => ({ [key]: value }))
.keys()
)

const env = {
APP_TOKEN: process.env.APP_TOKEN,
APP_PREFIX: process.env.APP_PREFIX,
return {
APP_TOKEN: process.env.APP_TOKEN!,
APP_PREFIX: process.env.APP_PREFIX!,
PARTIALS: partials,
MESSAGES: messages,
PRESETS: presets,
}
}

return env[key]
private async getFromJSON(file: File) {
const content = await file.getContent('utf-8')

return JSON.parse(content!.toString())
}

private getFromJSON (key: string) {
return JSON.parse(this.$env.content)[key]
private async getFromYAML(file: File) {
const content = await file.getContent('utf-8')

return YAML.load(content!.toString())
}

private getFromYAML (key: string) {
const env = YAML.load(this.$env.content)
return env[key]
public get(key: string) {
return this.$env.content[key]
}
}
}
19 changes: 16 additions & 3 deletions src/types/Factory.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
export type EnvironmentFactory = {
import { File } from 'fs-recursive'

export type EnvironmentElement = {
[key: string]: string | string[] | EnvironmentElement
}

export type Environment = {
type: string
path: string
content: string
content: EnvironmentElement
}

export type EnvironmentType = 'env' | 'json' | 'yaml'
export type EnvironmentType = 'env' | 'json' | 'yml' | 'yaml'

export interface EnvironmentFactory {
env: (file: File) => Promise<EnvironmentElement>
json: (file: File) => Promise<EnvironmentElement>
yml: (file: File) => Promise<EnvironmentElement>
yaml: (file: File) => Promise<EnvironmentElement>
}
30 changes: 18 additions & 12 deletions src/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
import { ClientEvents } from 'discord.js'
import File from 'fs-recursive/build/File'
import { File } from 'fs-recursive'
import HookEntity from '../entities/HookEntity'
import EventEntity from '../entities/EventEntity'
import MiddlewareEntity from '../entities/MiddlewareEntity'
import CommandEntity from '../entities/CommandEntity'

export type ContainerType = 'event' | 'command' | 'hook' | 'middleware' | 'slash-command' | null
export type ContainerType =
| 'event'
| 'command'
| 'hook'
| 'middleware'
| 'slash-command'
| null

export type Instance<K extends keyof ClientEvents> = HookEntity | EventEntity<K> | MiddlewareEntity | CommandEntity
export type Instance<K extends keyof ClientEvents> =
| HookEntity
| EventEntity<K>
| MiddlewareEntity
| CommandEntity

export type QueueItem = {
type: ContainerType
Expand All @@ -16,7 +26,11 @@ export type QueueItem = {
file: File
}

export type Context = HookEntity | EventEntity<any> | MiddlewareEntity | CommandEntity
export type Context =
| HookEntity
| EventEntity<any>
| MiddlewareEntity
| CommandEntity

export type Constructable<K extends keyof ClientEvents> = {
type: ContainerType
Expand All @@ -28,11 +42,3 @@ export type Constructable<K extends keyof ClientEvents> = {
export type CommandAlias = {
[key: string]: CommandEntity
}

export type EnvironmentFactory = {
type: string
path: string
content: string
}

export type EnvironmentType = 'env' | 'json' | 'yaml'
33 changes: 10 additions & 23 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -271,14 +271,6 @@
dependencies:
arrify "^1.0.1"

"@discord-factory/env@^0.0.0":
version "0.0.0"
resolved "https://registry.yarnpkg.com/@discord-factory/env/-/env-0.0.0.tgz#a4580fdeba63413ad03fb06604d69fa38c55ac9a"
integrity sha512-wIci20p+AtKoMgsUDAsuisQGtxbJc4wgYAwUXF4tMcX+mHa8R4PK1/8NLYeq8PVc1sn5NzEKyvE9Xc0jVuszbw==
dependencies:
dotenv "^9.0.0"
ts-node "^9.1.1"

"@discordjs/builders@^0.4.0":
version "0.4.0"
resolved "https://registry.yarnpkg.com/@discordjs/builders/-/builders-0.4.0.tgz#bb41573ce4824aa9194a53b52c29c5219b610010"
Expand Down Expand Up @@ -412,9 +404,9 @@
integrity sha512-3pwDJjp1PWacPTpH0LcfhgjvurQvrZFBrC6xxjaUEZ7ifUtT32jtjPxEMMblpqd2Mvx+k8haqQJLQxolyGN/cQ==

"@types/node@^16.3.3":
version "16.4.13"
resolved "https://registry.yarnpkg.com/@types/node/-/node-16.4.13.tgz#7dfd9c14661edc65cccd43a29eb454174642370d"
integrity sha512-bLL69sKtd25w7p1nvg9pigE4gtKVpGTPojBFLMkGHXuUgap2sLqQt2qUnqmVCDfzGUL0DRNZP+1prIZJbMeAXg==
version "16.6.1"
resolved "https://registry.yarnpkg.com/@types/node/-/node-16.6.1.tgz#aee62c7b966f55fc66c7b6dfa1d58db2a616da61"
integrity sha512-Sr7BhXEAer9xyGuCN3Ek9eg9xPviCF2gfu9kTfuU2HkTVAMYSDeX40fvpmo72n5nansg3nsBjuQBrsS28r+NUw==

"@types/normalize-package-data@^2.4.0":
version "2.4.0"
Expand All @@ -427,9 +419,9 @@
integrity sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA==

"@types/uuid@^8.3.0":
version "8.3.0"
resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-8.3.0.tgz#215c231dff736d5ba92410e6d602050cce7e273f"
integrity sha512-eQ9qFW/fhfGJF8WKHGEHZEyVWfZxrT+6CLIJGBcZPfxUh/+BnEj+UCGYMlr9qZuX/2AltsvwrGqp0LhEW8D0zQ==
version "8.3.1"
resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-8.3.1.tgz#1a32969cf8f0364b3d8c8af9cc3555b7805df14f"
integrity sha512-Y2mHTRAbqfFkpjldbkHGY8JIzRN6XqYRliG8/24FcHm2D2PwW24fl5xMRTVGdrb7iMrwCaIEbLWerGIkXuFWVg==

"@types/ws@^7.4.7":
version "7.4.7"
Expand Down Expand Up @@ -1437,11 +1429,6 @@ dotenv@^10.0.0:
resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-10.0.0.tgz#3d4227b8fb95f81096cdd2b66653fb2c7085ba81"
integrity sha512-rlBi9d8jpv9Sf1klPjNfFAuWDjKLwTIJJ/VxtoTwIR6hnZxcEOQCZg2oIL3MWBYw5GpUDKOEnND7LXTbIpQ03Q==

dotenv@^9.0.0:
version "9.0.2"
resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-9.0.2.tgz#dacc20160935a37dea6364aa1bef819fb9b6ab05"
integrity sha512-I9OvvrHp4pIARv4+x9iuewrWycX6CcZtoAu1XrzPxc5UygMJXJZYmBsynku8IkrJwgypE5DGNjDPmPRhDCptUg==

duplexer3@^0.1.4:
version "0.1.4"
resolved "https://registry.yarnpkg.com/duplexer3/-/duplexer3-0.1.4.tgz#ee01dd1cac0ed3cbc7fdbea37dc0a8f1ce002ce2"
Expand Down Expand Up @@ -2018,10 +2005,10 @@ flatted@^3.1.0:
resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.1.1.tgz#c4b489e80096d9df1dfc97c79871aea7c617c469"
integrity sha512-zAoAQiudy+r5SvnSw3KJy5os/oRJYHzrzja/tBDqrZtNhUw8bt6y8OBzMWcjWr+8liV8Eb6yOhw8WZ7VFZ5ZzA==

fs-recursive@1.1.4:
version "1.1.4"
resolved "https://registry.yarnpkg.com/fs-recursive/-/fs-recursive-1.1.4.tgz#93aab143c46b8b34f4a6e551adbf4c6939eba4bf"
integrity sha512-j3IHI8S9ady04a/r8VmAP5hjgQ+PbY3QWiJjQKgaSIxdyiKnSrGRbO6sewfy3OGVJLI37wi4wYRh7Kwj5r6X0w==
fs-recursive@1.1.7:
version "1.1.7"
resolved "https://registry.yarnpkg.com/fs-recursive/-/fs-recursive-1.1.7.tgz#598c956ead67acbb460f67b16a31dc0f7a62ca97"
integrity sha512-sJ6ic4Pg5+52LBcRImb8V5bvhlw4wfU2m95yvBU1SP3i79THLL9kJj6GEesRZuCUGPxS5LpncS+6hu25ZwIs5Q==
dependencies:
"@types/node" "^16.3.3"
"@types/uuid" "^8.3.0"
Expand Down

0 comments on commit a53e2d5

Please sign in to comment.