Skip to content

Commit

Permalink
Move to Now 2.0 (#54)
Browse files Browse the repository at this point in the history
* Fixed README.md

* Fixed description

* Added config

* Automatically fill cache

* Made interval work again

* Error properly for missing environment variables

* Correctly throw
  • Loading branch information
leo committed Jan 25, 2019
1 parent 13505cc commit 83baf0c
Show file tree
Hide file tree
Showing 10 changed files with 2,583 additions and 1,348 deletions.
11 changes: 11 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
root = true

[*]
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
end_of_line = lf
# editorconfig-tools is unable to ignore longs strings or urls
max_line_length = null
5 changes: 5 additions & 0 deletions .nowignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules
test
.circleci
.yarnrc
.gitignore
16 changes: 11 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,25 @@ The result will be faster and more lightweight than any other solution out there

## Usage

With [Now CLI](https://zeit.co/download), you can deploy an update server like this:
With [Now CLI](https://zeit.co/download), you can easily deploy an update server. As the first step, clone the repository:

```bash
now zeit/hazel
git clone https://github.com/zeit/hazel
```

Or if you have later versions of now-cli installed.
Next, move into the directory:

```bash
now -V 1 zeit/hazel
cd hazel
```

You'll be asked for the value of two environment variables:
Inside the directory, create a new deployment:

```bash
now -e ACCOUNT="<github-account>" -e REPOSITORY="<github-repository>"
```

On the command above, you can define the following environment variables:

- `ACCOUNT`: Your username or organisation name on GitHub
- `REPOSITORY`: The name of the repository to pull releases from
Expand Down
37 changes: 31 additions & 6 deletions lib/cache.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Packages
const fetch = require('node-fetch')
const convertStream = require('stream-to-string')
const ms = require('ms')

// Utilities
const checkPlatform = require('./platform')
Expand All @@ -11,19 +12,24 @@ module.exports = class Cache {
this.config = config

if (!account || !repository) {
throw new Error('Neither ACCOUNT, nor REPOSITORY are defined')
const error = new Error('Neither ACCOUNT, nor REPOSITORY are defined')
error.code = 'missing_configuration_properties'
throw error
}

if (token && !url) {
throw new Error(
'Neither NOW_URL, nor URL are defined, which are mandatory for private repo mode.'
)
const error = new Error('Neither NOW_URL, nor URL are defined, which are mandatory for private repo mode')
error.code = 'missing_configuration_properties'
throw error
}

this.latest = {}
this.lastUpdate = null;

this.cacheReleaseList = this.cacheReleaseList.bind(this)
this.refreshCache = this.refreshCache.bind(this)
this.loadCache = this.loadCache.bind(this)
this.isOutdated = this.isOutdated.bind(this)
}

async cacheReleaseList(url) {
Expand Down Expand Up @@ -92,6 +98,7 @@ module.exports = class Cache {

if (this.latest.version === tag_name) {
console.log('Cached version is the same as latest')
this.lastUpdate = Date.now()
return
}

Expand Down Expand Up @@ -137,12 +144,30 @@ module.exports = class Cache {
}

console.log(`Finished caching version ${tag_name}`)
this.lastUpdate = Date.now()
}

isOutdated() {
const { lastUpdate, config } = this
const { interval = 15 } = config

if (lastUpdate && (Date.now() - lastUpdate) > ms(`${interval}m`)) {
return true
}

return false
}

// This is a method returning the cache
// because the cache would otherwise be loaded
// only once when the index file is parsed
loadCache() {
return this.latest
async loadCache() {
const { latest, refreshCache, isOutdated, lastUpdate } = this

if (!lastUpdate || isOutdated()) {
await refreshCache()
}

return latest
}
}
38 changes: 20 additions & 18 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,35 @@
// Packages
const Router = require('router')
const finalhandler = require('finalhandler')
const ms = require('ms')
const Cache = require('./cache')

module.exports = config => {
// Utilities
const cache = new Cache(config)
const { refreshCache } = cache
const routes = require('./routes')({ cache, config })

// Initialize a new router
const router = Router()
let cache = null;

try {
cache = new Cache(config)
} catch (err) {
const { code, message } = err

if (code) {
return (req, res) => {
res.statusCode = 400;

const refresh = () => {
try {
refreshCache()
} catch (err) {
console.error(err)
res.end(JSON.stringify({
error: {
code,
message
}
}))
}
}
}

// Load most recent release
refresh()
throw err
}

// Refresh cache every 15 minutes or as defined
const { interval = 15 } = config
const routes = require('./routes')({ cache, config })

setInterval(refresh, ms(`${interval}m`))
// Define a route for every relevant path
router.get('/', routes.overview)
router.get('/download', routes.download)
Expand Down
26 changes: 14 additions & 12 deletions lib/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ module.exports = ({ cache, config }) => {
})
}

exports.download = (req, res) => {
exports.download = async (req, res) => {
const userAgent = parse(req.headers['user-agent'])
let platform

Expand All @@ -44,7 +44,7 @@ module.exports = ({ cache, config }) => {
}

// Get the latest version from the cache
const { platforms } = loadCache()
const { platforms } = await loadCache()

if (!platform || !platforms || !platforms[platform]) {
send(res, 404, 'No download available for your platform!')
Expand All @@ -63,11 +63,11 @@ module.exports = ({ cache, config }) => {
res.end()
}

exports.downloadPlatform = (req, res) => {
exports.downloadPlatform = async (req, res) => {
let { platform } = req.params

// Get the latest version from the cache
const latest = loadCache()
const latest = await loadCache()

// Check platform for appropiate aliases
platform = checkAlias(platform)
Expand All @@ -94,7 +94,7 @@ module.exports = ({ cache, config }) => {
res.end()
}

exports.update = (req, res) => {
exports.update = async (req, res) => {
const { platform: platformName, version } = req.params

if (!valid(version)) {
Expand All @@ -118,7 +118,7 @@ module.exports = ({ cache, config }) => {
}

// Get the latest version from the cache
const latest = loadCache()
const latest = await loadCache()

if (!latest.platforms || !latest.platforms[platform]) {
res.statusCode = 204
Expand Down Expand Up @@ -156,9 +156,9 @@ module.exports = ({ cache, config }) => {
res.end()
}

exports.releases = (req, res) => {
exports.releases = async (req, res) => {
// Get the latest version from the cache
const latest = loadCache()
const latest = await loadCache()

if (!latest.files || !latest.files.RELEASES) {
res.statusCode = 204
Expand All @@ -178,18 +178,20 @@ module.exports = ({ cache, config }) => {
}

exports.overview = async (req, res) => {
const latest = await loadCache()

try {
const render = await prepareView()

const details = {
account: config.account,
repository: config.repository,
date: distanceInWordsToNow(cache.latest.pub_date, { addSuffix: true }),
files: cache.latest.platforms,
version: cache.latest.version,
date: distanceInWordsToNow(latest.pub_date, { addSuffix: true }),
files: latest.platforms,
version: latest.version,
releaseNotes: `https://github.com/${config.account}/${
config.repository
}/releases/tag/${cache.latest.version}`,
}/releases/tag/${latest.version}`,
allReleases: `https://github.com/${config.account}/${
config.repository
}/releases`,
Expand Down
16 changes: 16 additions & 0 deletions now.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"version": 2,
"name": "hazel",
"builds": [
{
"src": "lib/server.js",
"use": "@now/node"
}
],
"routes": [
{
"src": ".*",
"dest": "/lib/server.js"
}
]
}
17 changes: 2 additions & 15 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
"main": "lib/index.js",
"description": "Lightweight update server for Electron apps",
"scripts": {
"start": "micro -p ${PORT:-3000} lib/server.js",
"dev": "micro-dev lib/server.js",
"test": "xo && jest",
"precommit": "lint-staged"
Expand All @@ -22,18 +21,6 @@
"no-await-in-loop": 0
}
},
"now": {
"env": [
"ACCOUNT",
"REPOSITORY"
],
"files": [
"lib",
"views",
"package-lock.json",
"package.json"
]
},
"lint-staged": {
"*.js": [
"yarn test",
Expand All @@ -47,8 +34,8 @@
"fetch": "1.1.0",
"finalhandler": "1.1.0",
"handlebars": "4.0.11",
"jest": "22.4.0",
"micro": "9.1.0",
"jest": "24.0.0",
"micro": "9.3.3",
"ms": "2.1.1",
"node-fetch": "2.0.0",
"router": "1.3.2",
Expand Down
6 changes: 2 additions & 4 deletions test/cache.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ describe('Cache', () => {
}

const cache = new Cache(config)
await cache.refreshCache()
const storage = cache.loadCache()
const storage = await cache.loadCache()

expect(typeof storage.version).toBe('string')
expect(typeof storage.platforms).toBe('object')
Expand All @@ -60,9 +59,8 @@ describe('Cache', () => {
}

const cache = new Cache(config)
await cache.refreshCache()
const storage = await cache.loadCache()

const storage = cache.loadCache()
console.log(storage.platforms.darwin)
})
})
Loading

0 comments on commit 83baf0c

Please sign in to comment.