Skip to content

Commit

Permalink
feat: auto install middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
aiji42 committed Jan 23, 2022
1 parent be5b739 commit 9c928f2
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
"main": "./build/index.js",
"module": "./esm/main.js",
"types": "./esm/main.d.ts",
"bin": {
"with-next-split": "./build/script.js"
},
"files": [
"build",
"esm"
Expand Down
52 changes: 52 additions & 0 deletions src/script.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#!/usr/bin/env node

import { statSync, unlinkSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'

const installMiddleware = (pagePath: string) => {
writeFileSync(
resolve(__dirname, '../..', pagePath, '_middleware.js'),
scriptText
)
}

const removeMiddleware = (pagePath: string) => {
;['js', 'ts'].forEach((ext) => {
const path = resolve(__dirname, '../..', pagePath, `_middleware.${ext}`)
if (
statSync(path, {
throwIfNoEntry: false
})
) {
unlinkSync(path)
}
})
}

const scriptText = `// NOTE: in this location, this file does nothing
// scripts/split.mjs will copy this file to /pages/_middleware.js at
// install/deploy if process.env.NEXT_SPLIT_ACTIVE == 1
export { middleware } from 'next-with-split'
`

const main = () => {
const command = process.argv[2]
const pagesPath = process.argv[3]

switch (command) {
case 'remove':
console.info(
`split traffic disabled, removing middleware from ${pagesPath}`
)
removeMiddleware(pagesPath)
break
case 'install':
console.info(
`split traffic enabled, installing middleware to ${pagesPath}`
)
installMiddleware(pagesPath)
break
}
}

main()

0 comments on commit 9c928f2

Please sign in to comment.