Skip to content

Commit

Permalink
feat: save state
Browse files Browse the repository at this point in the history
  • Loading branch information
unsync committed Jan 30, 2024
1 parent 7697bc1 commit 0416860
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ dist
coverage
.DS_Store
.config.json
.state.json
26 changes: 25 additions & 1 deletion src/veolia.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import fs from 'node:fs'
import { getLogger } from '@unsync/nodejs-tools'
import type { Dayjs } from 'dayjs'
import dayjs from 'dayjs'
Expand Down Expand Up @@ -34,6 +35,7 @@ export class VeoliaClient {
private xmlBuilder = new XMLBuilder({ ignoreAttributes: false })
private xmlParser = new XMLParser()
private logger = getLogger({ service: 'VeoliaClient' })
private stateFile = './.state.json'

constructor(config: VeoliaConfig) {
this.config = config
Expand Down Expand Up @@ -88,14 +90,20 @@ export class VeoliaClient {
const jsonObj = this.xmlParser.parse(responseBody)
let soapBody = this.getSoapResponse({ action: 'getConsommationJournaliere', jsonObj })

// create state file if not exists
const stateFile = this.getStateFile()

// filter data
if (firstDay) {
soapBody = soapBody.filter((r: any) => {
return dayjs(r.dateReleve).isAfter(firstDay, 'day')
})
}

return soapBody.map((r: any) => {
const result = soapBody.map((r: any) => {
if (!stateFile[r.dateReleve])
stateFile[r.dateReleve] = r

// regexp to extract date from string
const dateRegex = /(\d{4}-\d{2}-\d{2})T.*/
const dateReleveUTC = dayjs(dateRegex.exec(r.dateReleve)?.[1] || r.dateReleve).utc().add(12, 'hour')
Expand All @@ -112,12 +120,28 @@ export class VeoliaClient {
sum: index,
}
})

// save state
this.saveState(stateFile)

return result
} catch (e) {
this.logger.error(`VeoliaClient > getEnergyData > error: ${JSON.stringify(e)}`, e)
return []
}
}

private getStateFile() {
if (!fs.existsSync(this.stateFile))
fs.writeFileSync(this.stateFile, JSON.stringify({}))

return JSON.parse(fs.readFileSync(this.stateFile, 'utf8'))
}

private saveState(state: any) {
fs.writeFileSync(this.stateFile, JSON.stringify(state))
}

private getSoapResponse(_: { action: string, jsonObj: JSONValue }) {
// eslint-disable-next-line ts/ban-ts-comment
// @ts-expect-error
Expand Down

0 comments on commit 0416860

Please sign in to comment.