Skip to content

Commit

Permalink
refactor: use create require instead use global require
Browse files Browse the repository at this point in the history
Signed-off-by: Innei <[email protected]>
  • Loading branch information
Innei committed Sep 11, 2022
1 parent 748f4e6 commit 84099f3
Show file tree
Hide file tree
Showing 9 changed files with 132 additions and 22 deletions.
File renamed without changes.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,5 @@ schema.gql
app.config.js

webpack-dist

admin/
File renamed without changes.
64 changes: 64 additions & 0 deletions codemod/module-resolution-node-next.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import fs, { statSync } from 'fs'
import { resolve } from 'path'

const srcDir = resolve(process.cwd(), 'src')

const aliasMap = {
'~': srcDir,
}
/**
* every ts file relative import statement add `.js` ext
* @param dir
*/
function walkDir(dir: string) {
const files = fs.readdirSync(dir)
files.forEach((file) => {
const filePath = resolve(dir, file)
const stat = fs.statSync(filePath)
if (stat.isDirectory()) {
walkDir(filePath)
} else if (stat.isFile() && filePath.endsWith('.ts')) {
const content = fs.readFileSync(filePath, 'utf-8')

const newContent = content.replace(/from '(.*)'/g, (match, p1) => {
// if is startswith alphabet or @, this is a library path, return it

if (p1.startsWith('@') || /^[a-zA-Z]/.test(p1)) {
return match
}

// if this path is a folder, then add `/index.js` to the end

let path = ''
// if this path is a alias
if (p1.startsWith('~')) {
path = resolve(aliasMap['~'], p1.replace('~/', './'))
} else {
// if path is relative path
path = resolve(dir, p1)
}

console.log(path)

try {
const stat = statSync(path)
if (stat.isDirectory()) {
return `from '${p1}/index.js'`
}
} catch {}

if (p1.startsWith('.') || p1.startsWith('~')) {
return `from '${p1}.js'`
}
return match
})
fs.writeFileSync(filePath, newContent)
}
})
}

function main() {
walkDir(srcDir)
}

main()
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@
"prettier": "2.7.1",
"rimraf": "3.0.2",
"socket.io": "*",
"ts-jest": "29.0.0",
"ts-jest": "28.0.8",
"ts-node": "10.9.1",
"tsconfig-paths": "4.1.0",
"typescript": "4.7.4"
Expand Down
4 changes: 2 additions & 2 deletions paw.paw
Git LFS file not shown
49 changes: 40 additions & 9 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 22 additions & 9 deletions src/modules/serverless/serverless.service.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { isURL } from 'class-validator'
import fs, { mkdir, stat } from 'fs/promises'
import LRUCache from 'lru-cache'
import { createRequire } from 'module'
import { mongo } from 'mongoose'
import path from 'path'
import path, { resolve } from 'path'
import { nextTick } from 'process'

import { TransformOptions, parseAsync, transformAsync } from '@babel/core'
import BabelPluginTransformCommonJS from '@babel/plugin-transform-modules-commonjs'
import BabelPluginTransformTS from '@babel/plugin-transform-typescript'
import * as t from '@babel/types'
import { VariableDeclaration } from '@babel/types'
import {
Expand Down Expand Up @@ -232,6 +235,8 @@ export class ServerlessService {
const { raw: functionString } = model
const logger = new Logger(`fx:${model.reference}/${model.name}`)
const document = await this.model.findById(model.id)
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this
const globalContext = {
context: {
// inject app req, res
Expand Down Expand Up @@ -293,7 +298,7 @@ export class ServerlessService {

require: this.inNewContextRequire(),
get import() {
return this.require
return self.require
},

process: {
Expand Down Expand Up @@ -333,9 +338,9 @@ export class ServerlessService {
return {
comments: false,
plugins: [
require('@babel/plugin-transform-typescript'),
BabelPluginTransformTS,
[
require('@babel/plugin-transform-modules-commonjs'),
BabelPluginTransformCommonJS,
{ allowTopLevelThis: false, importInterop: 'node' },
],
function transformImport() {
Expand Down Expand Up @@ -411,25 +416,33 @@ export class ServerlessService {

private resolvePath(id: string) {
try {
return require.resolve(id)
return this.require.resolve(id)
} catch {
try {
const modulePath = path.resolve(NODE_REQUIRE_PATH, id)
const resolvePath = require.resolve(modulePath)
const resolvePath = this.require.resolve(modulePath)

return resolvePath
} catch {
} catch (err) {
delete this.require.cache[id]

isDev && console.error(err)

throw new InternalServerErrorException(`module "${id}" not found.`)
}
}
}

private require = isTest
? createRequire(resolve(process.cwd(), './node_modules'))
: createRequire(NODE_REQUIRE_PATH)

private inNewContextRequire() {
const __require = (id: string) => {
const isBuiltin = isBuiltinModule(id)

const resolvePath = this.resolvePath(id)
const module = require(resolvePath)
const module = this.require(resolvePath)
// TODO remove cache in-used package dependencies, because it will not exist in prod
// eslint-disable-next-line no-empty
if (Object.keys(PKG.dependencies).includes(id) || isBuiltin) {
Expand All @@ -441,7 +454,7 @@ export class ServerlessService {
}

const __requireNoCache = (id: string) => {
delete require.cache[this.resolvePath(id)]
delete this.require.cache[this.resolvePath(id)]
const clonedModule = __require(id)

return clonedModule
Expand Down
2 changes: 1 addition & 1 deletion test/src/modules/snippet/snippet.controller.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ describe('test /snippets', () => {
const json = res.json()
expect(res.statusCode).toBe(200)

expect(json).toStrictEqual(JSON.parse(mockPayload1.raw))
expect(json).toStrictEqual(JSON.parse(mockPayload1.raw || '{}'))
})
})

Expand Down

0 comments on commit 84099f3

Please sign in to comment.