Skip to content

Commit

Permalink
chore: add prettier (#101)
Browse files Browse the repository at this point in the history
  • Loading branch information
Rickard Natt och Dag authored Mar 30, 2021
1 parent 0edbc7e commit 19fd3dd
Show file tree
Hide file tree
Showing 23 changed files with 734 additions and 499 deletions.
9 changes: 4 additions & 5 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,17 @@ module.exports = {
parserOptions: {
ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features
sourceType: 'module', // Allows for the use of imports
project: ['./tsconfig.eslint.json']
project: ['./tsconfig.eslint.json'],
},
extends: [
'airbnb-typescript/base',
],
extends: ['airbnb-typescript/base', 'prettier'],
plugins: ['prettier'],
ignorePatterns: ['*.test.ts'],
rules: {
// Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
// e.g. "@typescript-eslint/explicit-function-return-type": "off",
// '@typescript-eslint/indent': ['error', 2],
'@typescript-eslint/semi': [2, 'never'],
'max-len': ['error', { code: 120, 'ignoreUrls': true }],
'max-len': ['error', { code: 120, ignoreUrls: true }],
'import/prefer-default-export': 0,
},
}
10 changes: 10 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": false,
"singleQuote": true,
"trailingComma": "es5",
"bracketSpacing": true,
"jsxBracketSameLine": false
}
34 changes: 17 additions & 17 deletions agentFetchWrapper.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
module.exports = function agentDecorator (fetch, agent) {
fetch = fetch || window.fetch
async function fetchWrapper (url, opts) {
opts = opts || {}
// Prepare request
opts.agent = agent
// Actual request
const res = await fetch(url, opts)
return res
}
return fetchWrapper
}
module.exports = function agentDecorator(fetch, agent) {
fetch = fetch || window.fetch

async function fetchWrapper(url, opts) {
opts = opts || {}

// Prepare request
opts.agent = agent

// Actual request
const res = await fetch(url, opts)

return res
}

return fetchWrapper
}
13 changes: 10 additions & 3 deletions devrun.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,13 @@ async function run() {
if (bankIdUsed) {
const sessionCookie = getSessionCookieFromCookieJar()
ensureDirectoryExistence('./record')
await writeFile('./record/latestSessionCookie.txt', JSON.stringify(sessionCookie))
console.log('Session cookie saved to file ./record/latesSessionCookie.txt')
await writeFile(
'./record/latestSessionCookie.txt',
JSON.stringify(sessionCookie)
)
console.log(
'Session cookie saved to file ./record/latesSessionCookie.txt'
)
}
console.log('user')
const user = await api.getUser()
Expand Down Expand Up @@ -116,7 +121,9 @@ async function Login(api) {
if (useBankId) {
console.log('*** BankId login - open BankId app ***')
if (!personalNumber) {
console.error('You must pass in a valid personal number, eg `node run 197001011111`')
console.error(
'You must pass in a valid personal number, eg `node run 197001011111`'
)
process.exit(1)
}
const status = await api.login(personalNumber)
Expand Down
4 changes: 2 additions & 2 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
transform: {
'.(ts|tsx)': 'ts-jest'
'.(ts|tsx)': 'ts-jest',
},
testRegex: '(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$',
moduleFileExtensions: ["ts", "tsx", "js"]
moduleFileExtensions: ['ts', 'tsx', 'js'],
}
20 changes: 11 additions & 9 deletions lib/__mocks__/@react-native-cookies/cookies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,14 @@ const convertTtoC = (cookie: string | TCookie): Cookie => {
name: cookie.key,
value: cookie.value,
domain: cookie.domain || undefined,
expires: cookie.expires === 'Infinity' ? undefined : cookie.expires.toUTCString(),
expires:
cookie.expires === 'Infinity' ? undefined : cookie.expires.toUTCString(),
httpOnly: cookie.httpOnly || undefined,
path: cookie.path || undefined,
secure: cookie.secure,
}
}
const convertCtoT = (cookie: Cookie): TCookie => (
const convertCtoT = (cookie: Cookie): TCookie =>
new TCookie({
key: cookie.name,
value: cookie.value,
Expand All @@ -48,13 +49,14 @@ const convertCtoT = (cookie: Cookie): TCookie => (
path: cookie.path,
secure: cookie.secure || false,
})
)
const convertCookies = (cookies: TCookie[]): Cookies => (
cookies.reduce((map, cookie) => ({
...map,
[cookie.key]: convertTtoC(cookie),
}), {} as Cookies)
)
const convertCookies = (cookies: TCookie[]): Cookies =>
cookies.reduce(
(map, cookie) => ({
...map,
[cookie.key]: convertTtoC(cookie),
}),
{} as Cookies
)

const jar = new CookieJar()
const CookieManager: CookieManagerStatic = {
Expand Down
8 changes: 4 additions & 4 deletions lib/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,17 +101,17 @@ describe('api', () => {
it('throws error on external api error', async () => {
expect.hasAssertions()

const data = ""
const data = ''
response.json.mockResolvedValue(data)
response.ok = false
response.status = 500
response.statusText = "Internal Server Error"
response.statusText = 'Internal Server Error'

const personalNumber = 'my personal number'
try {
await api.login(personalNumber)
} catch (error) {
expect(error.message).toEqual(expect.stringContaining("Server Error"))
expect(error.message).toEqual(expect.stringContaining('Server Error'))
}
})
})
Expand Down Expand Up @@ -170,7 +170,7 @@ describe('api', () => {
const user = await api.getUser()
expect(user).toEqual({
firstName: 'Namn',
lastName: 'Namnsson'
lastName: 'Namnsson',
})

const children = await api.getChildren()
Expand Down
68 changes: 47 additions & 21 deletions lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@ import { DateTime } from 'luxon'
import { EventEmitter } from 'events'
import { decode } from 'he'
import * as html from 'node-html-parser'
import {
checkStatus,
LoginStatusChecker,
} from './loginStatus'
import { checkStatus, LoginStatusChecker } from './loginStatus'
import {
AuthTicket,
CalendarItem,
Expand All @@ -25,9 +22,8 @@ import * as parse from './parse'
import wrap, { Fetcher, FetcherOptions } from './fetcher'
import * as fake from './fakeData'

const fakeResponse = <T>(data: T): Promise<T> => new Promise((res) => (
setTimeout(() => res(data), 200 + Math.random() * 800)
))
const fakeResponse = <T>(data: T): Promise<T> =>
new Promise((res) => setTimeout(() => res(data), 200 + Math.random() * 800))

export class Api extends EventEmitter {
private fetch: Fetcher
Expand All @@ -44,7 +40,11 @@ export class Api extends EventEmitter {

public childControllerUrl?: string

constructor(fetch: Fetch, cookieManager: CookieManager, options?: FetcherOptions) {
constructor(
fetch: Fetch,
cookieManager: CookieManager,
options?: FetcherOptions
) {
super()
this.fetch = wrap(fetch, options)
this.cookieManager = cookieManager
Expand All @@ -65,7 +65,10 @@ export class Api extends EventEmitter {
}
}

public async getSession(url: string, options?: RequestInit): Promise<RequestInit> {
public async getSession(
url: string,
options?: RequestInit
): Promise<RequestInit> {
const init = this.getRequestInit(options)
const cookie = await this.cookieManager.getCookieString(url)
return {
Expand Down Expand Up @@ -95,7 +98,9 @@ export class Api extends EventEmitter {
const ticketResponse = await this.fetch('auth-ticket', ticketUrl)

if (!ticketResponse.ok) {
throw new Error(`Server Error [${ticketResponse.status}] [${ticketResponse.statusText}] [${ticketUrl}]`)
throw new Error(
`Server Error [${ticketResponse.status}] [${ticketResponse.statusText}] [${ticketUrl}]`
)
}

const ticket: AuthTicket = await ticketResponse.json()
Expand All @@ -112,12 +117,14 @@ export class Api extends EventEmitter {
this.isLoggedIn = true
this.emit('login')
})
status.on('ERROR', () => { this.personalNumber = undefined })
status.on('ERROR', () => {
this.personalNumber = undefined
})

return status
}

public async setSessionCookie(sessionCookie : string) : Promise<void> {
public async setSessionCookie(sessionCookie: string): Promise<void> {
// Manually set cookie in this call and let the cookieManager
// handle it from here
// If we put it into the cookieManager manually, we get duplicate cookies
Expand Down Expand Up @@ -152,13 +159,17 @@ export class Api extends EventEmitter {
const response = await this.fetch('hemPage', url, session)
const text = await response.text()
const doc = html.parse(decode(text))
const xsrfToken = doc.querySelector('input[name="__RequestVerificationToken"]')?.getAttribute('value') || ''
const xsrfToken =
doc
.querySelector('input[name="__RequestVerificationToken"]')
?.getAttribute('value') || ''
const scriptTags = doc.querySelectorAll('script')
const childControllerScriptTag = scriptTags.find((elem) => {
const srcAttr = elem.getAttribute('src')
return srcAttr?.startsWith('/vardnadshavare/bundles/childcontroller')
})
this.childControllerUrl = routes.baseEtjanst + childControllerScriptTag?.getAttribute('src')
this.childControllerUrl =
routes.baseEtjanst + childControllerScriptTag?.getAttribute('src')
this.addHeader('x-xsrf-token', xsrfToken)
}

Expand All @@ -170,7 +181,8 @@ export class Api extends EventEmitter {

const apiKeyRegex = /"API-Key": "([\w\d]+)"/gm
const apiKeyMatches = apiKeyRegex.exec(text)
const apiKey = apiKeyMatches && apiKeyMatches.length > 1 ? apiKeyMatches[1] : ''
const apiKey =
apiKeyMatches && apiKeyMatches.length > 1 ? apiKeyMatches[1] : ''

this.addHeader('API-Key', apiKey)
}
Expand All @@ -192,12 +204,18 @@ export class Api extends EventEmitter {
}

private async retrieveCreateItemHeaders() {
const response = await this.fetch('createItemConfig', routes.createItemConfig)
const response = await this.fetch(
'createItemConfig',
routes.createItemConfig
)
const json = await response.json()
return json
}

private async retrieveAuthToken(url: string, authBody: string): Promise<string> {
private async retrieveAuthToken(
url: string,
authBody: string
): Promise<string> {
const session = this.getRequestInit({
method: 'POST',
headers: {
Expand Down Expand Up @@ -231,7 +249,9 @@ export class Api extends EventEmitter {
})

if (!response.ok) {
throw new Error(`Server Error [${response.status}] [${response.statusText}] [${url}]`)
throw new Error(
`Server Error [${response.status}] [${response.statusText}] [${url}]`
)
}

const authData = await response.json()
Expand Down Expand Up @@ -280,7 +300,9 @@ export class Api extends EventEmitter {
const response = await this.fetch('children', url, session)

if (!response.ok) {
throw new Error(`Server Error [${response.status}] [${response.statusText}] [${url}]`)
throw new Error(
`Server Error [${response.status}] [${response.statusText}] [${url}]`
)
}

const data = await response.json()
Expand All @@ -307,7 +329,11 @@ export class Api extends EventEmitter {
return parse.classmates(data)
}

public async getSchedule(child: Child, from: DateTime, to: DateTime): Promise<ScheduleItem[]> {
public async getSchedule(
child: Child,
from: DateTime,
to: DateTime
): Promise<ScheduleItem[]> {
if (this.isFake) return fakeResponse(fake.schedule(child))

const url = routes.schedule(child.sdsId, from.toISODate(), to.toISODate())
Expand Down Expand Up @@ -357,7 +383,7 @@ export class Api extends EventEmitter {
return parse.menuList(data)
}

private async getMenuChoice(child : Child) : Promise<string> {
private async getMenuChoice(child: Child): Promise<string> {
const url = routes.menuChoice(child.id)
const session = this.getRequestInit()
const response = await this.fetch('menu-choice', url, session)
Expand Down
Loading

0 comments on commit 19fd3dd

Please sign in to comment.