Skip to content

Instantly share code, notes, and snippets.

@Leko
Created November 3, 2018 07:00
Show Gist options
  • Save Leko/1a440e827e91ed309bb996408832fc64 to your computer and use it in GitHub Desktop.
Save Leko/1a440e827e91ed309bb996408832fc64 to your computer and use it in GitHub Desktop.
DO NOT USE IN PRODUCTION. It can only use for tests.
import assert from './assert'
import { runInTimezone } from './runInTimezone'

const offset = await runInTimezone('Asia/Tokyo', () => new Date().getTimezoneOffset())
assert.strictEquals(offset, -540)
if (typeof process.env.RUN_IN_TIMEZONE_CODE !== 'string') {
throw new Error('process.env.RUN_IN_TIMEZONE_CODE must be string')
}
// eslint-disable-next-line no-eval
const fn = eval(`(${process.env.RUN_IN_TIMEZONE_CODE})`)
if (typeof fn !== 'function') {
throw new Error('process.env.RUN_IN_TIMEZONE_CODE must be string of Function')
}
// eslint-disable-next-line no-undef
process.send(fn())
export const runInTimezone = (timezone: string, fn: Function): Promise<any> => {
const file = path.join(__dirname, 'eval-call.js')
return new Promise((resolve, reject) => {
const subprocess = fork(file, [], {
env: {
...process.env,
TZ: timezone,
RUN_IN_TIMEZONE_CODE: fn.toString(),
},
})
subprocess.on('message', resolve)
subprocess.on('error', reject)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment