Skip to content

Commit 6b28356

Browse files
chore: convert cache.js file within server to TypeScript (#31471)
* chore: convert cache.js file within server to TypeScript * update cache calls and await them * updates to imports and switching cache calls to await * remove Partial from Allowed State * change cache calls back to not await * Remove dead code * update memo.push return
1 parent 705580f commit 6b28356

File tree

14 files changed

+221
-342
lines changed

14 files changed

+221
-342
lines changed

.gitignore

+4-1
Original file line numberDiff line numberDiff line change
@@ -398,4 +398,7 @@ tooling/v8-snapshot/cache/prod-win32
398398
system-tests/lib/validations
399399

400400
.nx/cache
401-
.nx/workspace-data
401+
.nx/workspace-data
402+
403+
# IDE files
404+
.cursor

packages/data-context/src/data/coreDataShape.ts

+2-11
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { FoundBrowser, Editor, AllowedState, AllModeOptions, TestingType, BrowserStatus, PACKAGE_MANAGERS, AuthStateName, MIGRATION_STEPS, MigrationStep, BannerState, StudioManagerShape } from '@packages/types'
1+
import { FoundBrowser, Editor, AllowedState, AllModeOptions, TestingType, BrowserStatus, PACKAGE_MANAGERS, AuthStateName, MIGRATION_STEPS, MigrationStep, StudioManagerShape } from '@packages/types'
22
import { WizardBundler, CT_FRAMEWORKS, resolveComponentFrameworkDefinition, ErroredFramework } from '@packages/scaffold-config'
33
import type { NexusGenObjects } from '@packages/graphql/src/gen/nxs.gen'
44
// tslint:disable-next-line no-implicit-dependencies - electron dep needs to be defined
@@ -22,7 +22,7 @@ export interface AuthenticatedUserShape {
2222

2323
export interface ProjectShape {
2424
projectRoot: string
25-
savedState?: () => Promise<Maybe<SavedStateShape>>
25+
savedState?: () => Promise<AllowedState>
2626
}
2727

2828
export interface ServersDataShape {
@@ -47,15 +47,6 @@ export interface LocalSettingsDataShape {
4747
preferences: AllowedState
4848
}
4949

50-
export interface SavedStateShape {
51-
firstOpened?: number | null
52-
lastOpened?: number | null
53-
promptsShown?: object | null
54-
banners?: BannerState | null
55-
lastProjectId?: string | null
56-
specFilter?: string | null
57-
}
58-
5950
export interface ConfigChildProcessShape {
6051
/**
6152
* Child process executing the config & sourcing plugin events
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
1-
const _ = require('lodash')
2-
const Promise = require('bluebird')
3-
const { globalPubSub } = require('@packages/data-context')
4-
5-
const { fs } = require('./util/fs')
6-
const appData = require('./util/app_data')
7-
const FileUtil = require('./util/file')
1+
import _ from 'lodash'
2+
import Promise from 'bluebird'
3+
import { globalPubSub } from '@packages/data-context'
4+
import { fs } from './util/fs'
5+
import appData from './util/app_data'
6+
import FileUtil from './util/file'
7+
import type { Cache, CachedUser, Preferences, Cohort } from '@packages/types'
8+
9+
interface Transaction {
10+
get: <T = Cache>(key?: string, defaultValue?: T) => Promise<T>
11+
set: (key: string | Partial<Cache>, value?: any) => Promise<void>
12+
}
813

914
const fileUtil = new FileUtil({
1015
path: appData.path('cache'),
@@ -14,90 +19,52 @@ globalPubSub.on('test:cleanup', () => {
1419
fileUtil.__resetForTest()
1520
})
1621

17-
const convertProjectsToArray = function (obj) {
18-
// if our project structure is not
19-
// an array then its legacy and we
20-
// need to convert it
21-
if (!_.isArray(obj.PROJECTS)) {
22-
obj.PROJECTS = _.chain(obj.PROJECTS).values().map('PATH').compact().value()
23-
24-
return obj
25-
}
26-
}
27-
28-
const renameSessionToken = function (obj) {
29-
let st
30-
31-
if (obj.USER && (st = obj.USER.session_token)) {
32-
delete obj.USER.session_token
33-
obj.USER.sessionToken = st
34-
35-
return obj
36-
}
37-
}
38-
39-
module.exports = {
22+
export const cache = {
4023
path: fileUtil.path,
4124

42-
defaults () {
25+
defaults (): Cache {
4326
return {
44-
USER: {},
27+
USER: {
28+
authToken: '',
29+
name: '',
30+
email: '',
31+
},
4532
PROJECTS: [],
4633
PROJECT_PREFERENCES: {},
4734
PROJECTS_CONFIG: {},
4835
COHORTS: {},
4936
}
5037
},
5138

52-
_applyRewriteRules (obj = {}) {
53-
return _.reduce([convertProjectsToArray, renameSessionToken], (memo, fn) => {
54-
let ret
55-
56-
ret = fn(memo)
57-
58-
if (ret) {
59-
return ret
60-
}
61-
62-
return memo
63-
}
64-
, _.cloneDeep(obj))
65-
},
66-
67-
read () {
39+
_read (): Promise<Cache> {
6840
return fileUtil.get().then((contents) => {
6941
return _.defaults(contents, this.defaults())
7042
})
7143
},
7244

73-
write (obj = {}) {
74-
return fileUtil.set(obj).return(obj)
75-
},
76-
77-
_getProjects (tx) {
45+
_getProjects (tx: Transaction): Promise<string[]> {
7846
return tx.get('PROJECTS', [])
7947
},
8048

81-
_removeProjects (tx, projects, paths) {
82-
// normalize paths in array
83-
projects = _.without(projects, ...[].concat(paths))
49+
_removeProjects (tx: Transaction, projects: string[], paths: string | string[]): Promise<void> {
50+
const pathsArray = Array.isArray(paths) ? paths : [paths]
51+
52+
projects = _.without(projects, ...pathsArray)
8453

8554
return tx.set({ PROJECTS: projects })
8655
},
8756

88-
/**
89-
* @return {Promise<string[]>}
90-
*/
91-
getProjectRoots () {
92-
return fileUtil.transaction((tx) => {
57+
getProjectRoots (): Promise<string[]> {
58+
return fileUtil.transaction((tx: Transaction) => {
9359
return this._getProjects(tx).then((projects) => {
94-
const pathsToRemove = Promise.reduce(projects, (memo, path) => {
60+
const pathsToRemove = Promise.reduce(projects, (memo: string[], path) => {
9561
return fs.statAsync(path)
9662
.catch(() => {
97-
return memo.push(path)
63+
memo.push(path)
64+
65+
return memo
9866
}).return(memo)
99-
}
100-
, [])
67+
}, [])
10168

10269
return pathsToRemove.then((removedPaths) => {
10370
return this._removeProjects(tx, projects, removedPaths)
@@ -108,16 +75,16 @@ module.exports = {
10875
})
10976
},
11077

111-
removeProject (path) {
112-
return fileUtil.transaction((tx) => {
78+
removeProject (path: string): Promise<void> {
79+
return fileUtil.transaction((tx: Transaction) => {
11380
return this._getProjects(tx).then((projects) => {
11481
return this._removeProjects(tx, projects, path)
11582
})
11683
})
11784
},
11885

119-
insertProject (path) {
120-
return fileUtil.transaction((tx) => {
86+
insertProject (path: string): Promise<void> {
87+
return fileUtil.transaction((tx: Transaction) => {
12188
return this._getProjects(tx).then((projects) => {
12289
// projects are sorted by most recently used, so add a project to
12390
// the start or move it to the start if it already exists
@@ -136,28 +103,28 @@ module.exports = {
136103
})
137104
},
138105

139-
getUser () {
106+
getUser (): Promise<CachedUser> {
140107
return fileUtil.get('USER', {})
141108
},
142109

143-
setUser (user) {
110+
setUser (user: CachedUser): Promise<void> {
144111
return fileUtil.set({ USER: user })
145112
},
146113

147-
removeUser () {
114+
removeUser (): Promise<void> {
148115
return fileUtil.set({ USER: {} })
149116
},
150117

151-
removeLatestProjects () {
118+
removeLatestProjects (): Promise<void> {
152119
return fileUtil.set({ PROJECTS: [] })
153120
},
154121

155-
getProjectPreferences () {
122+
getProjectPreferences (): Promise<Record<string, Preferences>> {
156123
return fileUtil.get('PROJECT_PREFERENCES', {})
157124
},
158125

159-
insertProjectPreferences (projectTitle, projectPreferences) {
160-
return fileUtil.transaction((tx) => {
126+
insertProjectPreferences (projectTitle: string, projectPreferences: Preferences): Promise<void> {
127+
return fileUtil.transaction((tx: Transaction) => {
161128
return tx.get('PROJECT_PREFERENCES', {}).then((preferences) => {
162129
return tx.set('PROJECT_PREFERENCES', {
163130
...preferences,
@@ -170,11 +137,11 @@ module.exports = {
170137
})
171138
},
172139

173-
removeAllProjectPreferences () {
140+
removeAllProjectPreferences (): Promise<void> {
174141
return fileUtil.set({ PROJECT_PREFERENCES: {} })
175142
},
176143

177-
removeProjectPreferences (projectTitle) {
144+
removeProjectPreferences (projectTitle: string): Promise<void> {
178145
const preferences = fileUtil.get('PROJECT_PREFERENCES', {})
179146

180147
const updatedPreferences = {
@@ -185,7 +152,7 @@ module.exports = {
185152
return fileUtil.set({ PROJECT_PREFERENCES: updatedPreferences })
186153
},
187154

188-
getCohorts () {
155+
getCohorts (): Promise<Record<string, Cohort>> {
189156
return fileUtil.get('COHORTS', {}).then((cohorts) => {
190157
Object.keys(cohorts).forEach((key) => {
191158
cohorts[key].name = key
@@ -195,8 +162,8 @@ module.exports = {
195162
})
196163
},
197164

198-
insertCohort (cohort) {
199-
return fileUtil.transaction((tx) => {
165+
insertCohort (cohort: Cohort): Promise<void> {
166+
return fileUtil.transaction((tx: Transaction) => {
200167
return tx.get('COHORTS', {}).then((cohorts) => {
201168
return tx.set('COHORTS', {
202169
...cohorts,
@@ -208,11 +175,10 @@ module.exports = {
208175
})
209176
},
210177

211-
remove () {
178+
remove (): Promise<void> {
212179
return fileUtil.remove()
213180
},
214181

215182
// for testing purposes
216-
217-
__get: fileUtil.get.bind(fileUtil),
183+
__get: fileUtil.get.bind(fileUtil) as <T = Cache>(key?: string, defaultValue?: T) => Promise<T>,
218184
}

packages/server/lib/cloud/user.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
const api = require('./api').default
2-
const cache = require('../cache')
2+
const { cache } = require('../cache')
33

44
import type { CachedUser } from '@packages/types'
55
import type Bluebird from 'bluebird'

packages/server/lib/cohorts.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const cache = require('./cache')
1+
import { cache } from './cache'
22
import type { Cohort } from '@packages/types'
33
const debug = require('debug')('cypress:server:cohorts')
44

packages/server/lib/makeDataContext.ts

+2-4
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import auth from './cloud/auth'
2020
import user from './cloud/user'
2121
import cohorts from './cohorts'
2222
import { openProject } from './open_project'
23-
import cache from './cache'
23+
import { cache } from './cache'
2424
import { graphqlSchema } from '@packages/graphql/src/schema'
2525
import { openExternal } from './gui/links'
2626
import { getUserEditor } from './util/editors'
@@ -109,9 +109,7 @@ export function makeDataContext (options: MakeDataContextOptions): DataContext {
109109
return cache.removeAllProjectPreferences()
110110
},
111111
insertProjectPreferencesToCache (projectTitle: string, preferences: Preferences) {
112-
// FIXME: this should be awaited (since it writes to disk asynchronously) but is not
113-
// https://cypress-io.atlassian.net/browse/UNIFY-1705
114-
cache.insertProjectPreferences(projectTitle, preferences)
112+
return cache.insertProjectPreferences(projectTitle, preferences)
115113
},
116114
removeProjectFromCache (path: string) {
117115
return cache.removeProject(path)

packages/server/test/integration/cypress_spec.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ const interactiveMode = require(`../../lib/modes/interactive`)
2727
const api = require(`../../lib/cloud/api`).default
2828
const cwd = require(`../../lib/cwd`)
2929
const user = require(`../../lib/cloud/user`)
30-
const cache = require(`../../lib/cache`)
30+
const cache = require(`../../lib/cache`).cache
3131
const errors = require(`../../lib/errors`)
3232
const cypress = require(`../../lib/cypress`)
3333
const ProjectBase = require(`../../lib/project-base`).ProjectBase

packages/server/test/spec_helper.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ global.proxyquire = require('proxyquire')
1616
global.sinon = require('sinon')
1717
const _ = require('lodash')
1818
const Promise = require('bluebird')
19-
const cache = require('../lib/cache')
19+
const cache = require('../lib/cache').cache
2020

2121
require('chai')
2222
.use(require('@cypress/sinon-chai'))

0 commit comments

Comments
 (0)