Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(deps): use neostandard over standard #120

Merged
merged 2 commits into from
Aug 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 0 additions & 33 deletions .eslintrc.js

This file was deleted.

4 changes: 2 additions & 2 deletions enum/EFiles.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = Object.freeze({
BADGES: 'badges.json',
BADGES_MIN: 'badges.min.json'
BADGES: 'badges.json',
BADGES_MIN: 'badges.min.json'
})
2 changes: 1 addition & 1 deletion enum/EFolders.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const path = require('path')

module.exports = Object.freeze({
DATA: path.resolve(__dirname, '../data')
DATA: path.resolve(__dirname, '../data')
})
2 changes: 1 addition & 1 deletion enum/ELocales.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module.exports = Object.freeze({
en_US: 'en-US'
en_US: 'en-US'
})
19 changes: 19 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use strict'

const jest = require('eslint-plugin-jest')
const neostandard = require('neostandard')

module.exports = [
...neostandard(),
{
files: ['lib/__tests__/**'],
...jest.configs['flat/recommended'],
rules: {
// Keep 'flat/recommended' below so rules will take precedence over 'flat/style' or any other
// just in case that the same rule is defined in both places with different error level
// i.e. jest/no-alias-methods rule
...jest.configs['flat/style'].rules,
...jest.configs['flat/recommended'].rules
}
}
]
20 changes: 10 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@ const EFolders = require('./enum/EFolders')
const EFiles = require('./enum/EFiles')
const ELocales = require('./enum/ELocales')

async function main() {
Logger.info('Connecting to SteamCardExchange...')
const sce = await SteamCardExchange.getBadges()
const cache = JSONStorage.readSync(EFolders.DATA, EFiles.BADGES)
const badges = { ...cache, ...sce }
async function main () {
Logger.info('Connecting to SteamCardExchange...')
const sce = await SteamCardExchange.getBadges()
const cache = JSONStorage.readSync(EFolders.DATA, EFiles.BADGES)
const badges = { ...cache, ...sce }

const count = Object.keys(badges).length
const countAsString = count.toLocaleString(ELocales.en_US)
Logger.info(`Found ${countAsString} Steam apps having trading cards.`)
const count = Object.keys(badges).length
const countAsString = count.toLocaleString(ELocales.en_US)
Logger.info(`Found ${countAsString} Steam apps having trading cards.`)

JSONStorage.writeSync(EFolders.DATA, EFiles.BADGES, badges, { minify: false })
JSONStorage.writeSync(EFolders.DATA, EFiles.BADGES_MIN, badges)
JSONStorage.writeSync(EFolders.DATA, EFiles.BADGES, badges, { minify: false })
JSONStorage.writeSync(EFolders.DATA, EFiles.BADGES_MIN, badges)
}

main()
20 changes: 10 additions & 10 deletions lib/HTTPClient.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
class HTTPException {
static throwIfFailed(response) {
if (!response.ok) {
throw new Error(`HTTP-${response.status} ${response.statusText}`)
}
static throwIfFailed (response) {
if (!response.ok) {
throw new Error(`HTTP-${response.status} ${response.statusText}`)
}
}
}

class HTTPClient {
static getJSON(url) {
return fetch(url).then(response => {
HTTPException.throwIfFailed(response)
return response.json()
})
}
static getJSON (url) {
return fetch(url).then(response => {
HTTPException.throwIfFailed(response)
return response.json()
})
}
}

module.exports = HTTPClient
32 changes: 16 additions & 16 deletions lib/JSONStorage.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,27 @@ const fs = require('fs')
const path = require('path')

class JSONStorage {
static writeSync(dir, filename, data, options) {
const defaults = { minify: true }
options = { ...defaults, ...options }
static writeSync (dir, filename, data, options) {
const defaults = { minify: true }
options = { ...defaults, ...options }

if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
const filePath = path.join(dir, filename)
const json = JSON.stringify(data, null, options.minify ? 0 : 4)
fs.writeFileSync(filePath, json)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
const filePath = path.join(dir, filename)
const json = JSON.stringify(data, null, options.minify ? 0 : 4)
fs.writeFileSync(filePath, json)
}

static readSync(dir, filename) {
const filePath = path.join(dir, filename)
static readSync (dir, filename) {
const filePath = path.join(dir, filename)

if (!fs.existsSync(filePath)) {
throw new Error('File Not Found')
}
const data = fs.readFileSync(filePath, { encoding: 'utf8' })
return JSON.parse(data)
if (!fs.existsSync(filePath)) {
throw new Error('File Not Found')
}
const data = fs.readFileSync(filePath, { encoding: 'utf8' })
return JSON.parse(data)
}
}

module.exports = JSONStorage
12 changes: 6 additions & 6 deletions lib/Logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@ const { createLogger, format, transports } = require('winston')
const console = new transports.Console()

const timestamp = format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss'
format: 'YYYY-MM-DD HH:mm:ss'
})

const printf = format.printf(info => {
return `[${info.timestamp}] [${info.level.toUpperCase()}] ${info.message}`
return `[${info.timestamp}] [${info.level.toUpperCase()}] ${info.message}`
})

const colorize = format.printf(info => {
return format.colorize().colorize(info.level, info[Symbol.for('message')])
return format.colorize().colorize(info.level, info[Symbol.for('message')])
})

module.exports = createLogger({
level: 'debug',
format: format.combine(timestamp, printf, colorize),
transports: [console]
level: 'debug',
format: format.combine(timestamp, printf, colorize),
transports: [console]
})
32 changes: 16 additions & 16 deletions lib/SteamCardExchange.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,26 @@ const { decode } = require('html-entities')
const { getJSON } = require('./HTTPClient')

class SteamCardExchange {
static async getBadges() {
const endpoint = 'https://www.steamcardexchange.net/api/request.php?GetInventory'
const data = await getJSON(endpoint).then(json => json.data)
static async getBadges () {
const endpoint = 'https://www.steamcardexchange.net/api/request.php?GetInventory'
const data = await getJSON(endpoint).then(json => json.data)

if (!data) {
throw new Error('Malformed response')
}
if (!data) {
throw new Error('Malformed response')
}

return data.reduce((badges, current) => {
const appid = current[0][0]
const name = decode(current[0][1])
const size = current[3][0]
return data.reduce((badges, current) => {
const appid = current[0][0]
const name = decode(current[0][1])
const size = current[3][0]

if (size) {
badges[appid] = { name, size }
}
if (size) {
badges[appid] = { name, size }
}

return badges
}, {})
}
return badges
}, {})
}
}

module.exports = SteamCardExchange
34 changes: 17 additions & 17 deletions lib/__tests__/HTTPClient.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,32 @@ const { getJSON } = require('../HTTPClient')
const fetchSpy = jest.spyOn(global, 'fetch')

const mockFechSuccess = Promise.resolve({
json: () => Promise.resolve({ foo: 'bar' }), // response content that was provided by the server as json format
ok: true, // whether the response was successful (status in the range 200-299) or not
status: 200, // HTTP status code from the server response
statusText: 'OK' // HTTP status message from the server response
json: () => Promise.resolve({ foo: 'bar' }), // response content that was provided by the server as json format
ok: true, // whether the response was successful (status in the range 200-299) or not
status: 200, // HTTP status code from the server response
statusText: 'OK' // HTTP status message from the server response
})

const mockFechFailure = Promise.resolve({
json: async () => {}, // response content that was provided by the server as json format
ok: false, // whether the response was successful (status in the range 200-299) or not
status: 404, // HTTP status code from the server response
statusText: 'Not Found' // HTTP status message from the server response
json: async () => {}, // response content that was provided by the server as json format
ok: false, // whether the response was successful (status in the range 200-299) or not
status: 404, // HTTP status code from the server response
statusText: 'Not Found' // HTTP status message from the server response
})

describe('HTTPClient#getJSON()', () => {
test('Throws "HTTP" error', async () => {
fetchSpy.mockImplementationOnce(() => mockFechFailure)
await expect(getJSON()).rejects.toThrow('HTTP-404 Not Found')
})
test('Throws "HTTP" error', async () => {
fetchSpy.mockImplementationOnce(() => mockFechFailure)
await expect(getJSON()).rejects.toThrow('HTTP-404 Not Found')
})

test('Fetch JSON successfully', async () => {
fetchSpy.mockImplementationOnce(() => mockFechSuccess)
await expect(getJSON()).resolves.toStrictEqual({ foo: 'bar' })
})
test('Fetch JSON successfully', async () => {
fetchSpy.mockImplementationOnce(() => mockFechSuccess)
await expect(getJSON()).resolves.toStrictEqual({ foo: 'bar' })
})
})

// Runs after all the tests in this file have completed.
afterAll(() => {
fetchSpy.mockRestore()
fetchSpy.mockRestore()
})
64 changes: 32 additions & 32 deletions lib/__tests__/JSONStorage.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,50 +4,50 @@ const { vol } = require('memfs')
jest.mock('fs', () => require('memfs').fs)

beforeEach(() => {
jest.resetAllMocks()
vol.reset() // Reset in-memory filesystem
jest.resetAllMocks()
vol.reset() // Reset in-memory filesystem
})

describe('JSONStorage#readSync()', () => {
test('Throw "File Not Found" error', () => {
const readSync = () => JSONStorage.readSync('/foo', 'bar.txt')
expect(readSync).toThrow('File Not Found')
})

test('Load json file successfully', () => {
const data = { key: 'value' }
vol.fromJSON({
'./file.json': JSON.stringify(data)
})
const readSync = () => JSONStorage.readSync('.', 'file.json')
expect(readSync()).toStrictEqual(data)
test('Throw "File Not Found" error', () => {
const readSync = () => JSONStorage.readSync('/foo', 'bar.txt')
expect(readSync).toThrow('File Not Found')
})

test('Load json file successfully', () => {
const data = { key: 'value' }
vol.fromJSON({
'./file.json': JSON.stringify(data)
})
const readSync = () => JSONStorage.readSync('.', 'file.json')
expect(readSync()).toStrictEqual(data)
})
})

describe('JSONStorage#writeSync()', () => {
test('Save json data successfully (compress)', () => {
const data = { key: 'value' }
const filename = 'file.min.json'
const folder = '/folder'
test('Save json data successfully (compress)', () => {
const data = { key: 'value' }
const filename = 'file.min.json'
const folder = '/folder'

JSONStorage.writeSync(folder, filename, data)
JSONStorage.writeSync(folder, filename, data)

const result = vol.toJSON()['/folder/file.min.json']
const expected = JSON.stringify(data)
const result = vol.toJSON()['/folder/file.min.json']
const expected = JSON.stringify(data)

expect(result).toBe(expected)
})
expect(result).toBe(expected)
})

test('Save json data successfully (pretty-print)', () => {
const data = { key: 'value' }
const filename = 'file.json'
const folder = '/folder'
test('Save json data successfully (pretty-print)', () => {
const data = { key: 'value' }
const filename = 'file.json'
const folder = '/folder'

JSONStorage.writeSync(folder, filename, data, { minify: false })
JSONStorage.writeSync(folder, filename, data, { minify: false })

const result = vol.toJSON()['/folder/file.json']
const expected = JSON.stringify(data, null, 4)
const result = vol.toJSON()['/folder/file.json']
const expected = JSON.stringify(data, null, 4)

expect(result).toBe(expected)
})
expect(result).toBe(expected)
})
})
Loading