@1auth/store-sql 0.0.0-alpha.6 → 0.0.0-alpha.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.js +141 -25
  2. package/package.json +8 -5
  3. package/LICENSE +0 -21
package/index.js CHANGED
@@ -1,9 +1,14 @@
1
1
  const options = {
2
2
  log: false,
3
- query: (sql, parameters) => {
4
- console.log('sql', sql, parameters)
5
- return {}
6
- }
3
+ query: undefined, // async (sql, parameters) => {}
4
+ // number of seconds after expire before removal
5
+ // 10d chosen based on EFF DNT Policy
6
+ timeToLiveExpireOffset: 10 * 24 * 60 * 60,
7
+ timeToLiveKey: 'remove',
8
+ // mode:
9
+ // ?: use `?` for variables, ie sqlite
10
+ // $: use `$1` for variables, ie postgres
11
+ placeholder: '?'
7
12
  }
8
13
 
9
14
  export default (params) => {
@@ -11,30 +16,106 @@ export default (params) => {
11
16
  }
12
17
 
13
18
  export const exists = async (table, filters) => {
14
- const item = await select(table, filters)
15
- return item?.sub
19
+ if (options.log) {
20
+ options.log('@1auth/store-sql exists(', table, filters, ')')
21
+ }
22
+ const { select, where, parameters } = makeSqlParts(filters, {}, ['sub'])
23
+ const sql = `SELECT ${select} FROM ${table} ${where} LIMIT 1`
24
+ return await options.query(sql, parameters).then((res) => res?.[0]?.sub)
16
25
  }
17
26
 
18
- export const selectList = async (table, filters = {}, fields = []) => {
19
- const { select, where, parameters } = makeSqlParts(filters, {}, fields)
20
- const sql = `SELECT ${select} FROM ${table} ${where}`
21
- return await options.query(sql, parameters)
27
+ export const count = async (table, filters = {}) => {
28
+ if (options.log) {
29
+ options.log('@1auth/store-sql count(', table, filters, ')')
30
+ }
31
+ const { where, parameters } = makeSqlParts(filters, {})
32
+ const sql = `SELECT COUNT(*) AS count FROM ${table} ${where}`
33
+ return await options.query(sql, parameters).then((res) => res[0].count)
22
34
  }
23
35
 
24
36
  export const select = async (table, filters = {}, fields = []) => {
37
+ if (options.log) {
38
+ options.log('@1auth/store-sql select(', table, filters, fields, ')')
39
+ }
25
40
  const { select, where, parameters } = makeSqlParts(filters, {}, fields)
26
41
  const sql = `SELECT ${select} FROM ${table} ${where} LIMIT 1`
27
- return await options.query(sql, parameters).then((res) => res[0])
42
+ return await options
43
+ .query(sql, parameters)
44
+ .then((res) => res?.[0])
45
+ // Workaround because an expire filter doesn't exists yet'
46
+ .then((row) => {
47
+ parseValues(row)
48
+ return row
49
+ })
50
+ }
51
+
52
+ export const selectList = async (table, filters = {}, fields = []) => {
53
+ if (options.log) {
54
+ options.log('@1auth/store-sql selectList(', table, filters, fields, ')')
55
+ }
56
+ const { select, where, parameters } = makeSqlParts(filters, {}, fields)
57
+ const sql = `SELECT ${select} FROM ${table} ${where}`
58
+ return await options
59
+ .query(sql, parameters)
60
+ // Workaround because an expire filter doesn't exists yet'
61
+ .then((rows) => {
62
+ return rows.map((row) => {
63
+ parseValues(row)
64
+ return row
65
+ })
66
+ })
28
67
  }
29
68
 
30
69
  export const insert = async (table, values = {}) => {
70
+ if (options.log) {
71
+ options.log('@1auth/store-sql insert(', table, values, ')')
72
+ }
73
+ if (values.expire && options.timeToLiveKey) {
74
+ values[options.timeToLiveKey] =
75
+ values.expire + options.timeToLiveExpireOffset
76
+ }
77
+ values = structuredClone(values)
31
78
  normalizeValues(values)
32
79
  const { insert, parameters } = makeSqlParts({}, values)
33
- const sql = `INSERT INTO ${table} ${insert}`
34
- return await options.query(sql, parameters).then((res) => res.id)
80
+ const sql = `INSERT INTO ${table} ${insert} RETURNING id`
81
+ const res = await options.query(sql, parameters)
82
+ return res.id
83
+ }
84
+
85
+ export const insertList = async (table, rows = []) => {
86
+ if (options.log) {
87
+ options.log('@1auth/store-sql insertList(', table, rows, ')')
88
+ }
89
+ const insertValues = []
90
+ let insertParameters = []
91
+ for (let i = 0, l = rows.length; i < l; i++) {
92
+ const values = structuredClone(rows[i])
93
+ normalizeValues(values)
94
+ const { insert, parameters } = makeSqlParts(
95
+ {},
96
+ values,
97
+ [],
98
+ i * Object.keys(values).length + 1
99
+ )
100
+ if (i) {
101
+ insertValues.push(insert.split('VALUES')[1]) // (?)
102
+ } else {
103
+ insertValues.push(insert) // (name) VALUES (?)
104
+ }
105
+
106
+ insertParameters = insertParameters.concat(parameters)
107
+ }
108
+
109
+ const sql = `INSERT INTO ${table} ${insertValues.join(',')} RETURNING id`
110
+ const res = await options.query(sql, insertParameters)
111
+ return res
35
112
  }
36
113
 
37
114
  export const update = async (table, filters = {}, values = {}) => {
115
+ if (options.log) {
116
+ options.log('@1auth/store-sql update(', table, filters, values, ')')
117
+ }
118
+ values = structuredClone(values)
38
119
  normalizeValues(values)
39
120
  const { update, where, parameters } = makeSqlParts(filters, values)
40
121
  const sql = `UPDATE ${table} SET ${update} ${where}`
@@ -42,56 +123,91 @@ export const update = async (table, filters = {}, values = {}) => {
42
123
  }
43
124
 
44
125
  export const remove = async (table, filters = {}) => {
126
+ if (options.log) {
127
+ options.log('@1auth/store-sql remove(', table, filters, ')')
128
+ }
45
129
  const { where, parameters } = makeSqlParts(filters)
46
130
  const sql = `DELETE FROM ${table} ${where}`
47
131
  await options.query(sql, parameters)
48
132
  }
49
133
 
50
134
  const normalizeValues = (values) => {
135
+ if (!values) return
51
136
  values.create &&= new Date(values.create * 1000).toISOString()
52
137
  values.update &&= new Date(values.update * 1000).toISOString()
53
138
  values.verify &&= new Date(values.verify * 1000).toISOString()
139
+ values.lastused &&= new Date(values.lastused * 1000).toISOString()
54
140
  values.expire &&= new Date(values.expire * 1000).toISOString()
141
+ values.remove &&= new Date(values.remove * 1000).toISOString()
142
+ }
143
+
144
+ const parseValues = (values) => {
145
+ if (!values) return
146
+ values.create &&= Date.parse(values.create) / 1000
147
+ values.update &&= Date.parse(values.update) / 1000
148
+ values.verify &&= Date.parse(values.verify) / 1000
149
+ values.lastused &&= Date.parse(values.lastused) / 1000
150
+ values.expire &&= Date.parse(values.expire) / 1000
151
+ values.remove &&= Date.parse(values.remove) / 1000
55
152
  }
56
153
 
57
154
  // export for testing
58
- export const makeSqlParts = (filters = {}, values = {}, fields = []) => {
155
+ export const getPlaceholder = (idx) => {
156
+ return options.placeholder === '$' ? '$' + idx : options.placeholder
157
+ }
158
+ export const makeSqlParts = (
159
+ filters = {},
160
+ values = {},
161
+ fields = [],
162
+ idx = 1
163
+ ) => {
59
164
  let parameters = []
60
- let idx = 1
61
165
  const keys = Object.keys(values)
62
166
 
63
- const select = fields.length ? fields.join(', ') : '*'
167
+ const select = fields.length ? '"' + fields.join('", "') + '"' : '*'
64
168
 
65
169
  const insertParts = []
66
170
  const updateParts = []
67
171
  for (const key of keys) {
68
- insertParts.push('$' + idx)
69
- updateParts.push(key + ' = $' + idx)
172
+ // insertParts.push("$" + idx);
173
+ // updateParts.push('"' + key + '" = $' + idx);
174
+ insertParts.push(getPlaceholder(idx))
175
+ updateParts.push('"' + key + '" = ' + getPlaceholder(idx))
70
176
  idx++
71
177
  }
72
-
73
178
  const insert =
74
- '("' + keys.join('", "') + '") VALUES (' + insertParts.join(', ') + ')'
75
-
179
+ '("' + keys.join('", "') + '") VALUES (' + insertParts.join(',') + ')'
76
180
  const update = updateParts.join(', ')
77
-
78
181
  parameters = parameters.concat(Object.values(values))
79
182
 
80
183
  let where = Object.keys(filters)
81
184
  where = where
82
185
  .map((key) => {
83
186
  if (Array.isArray(filters[key])) {
84
- let sql = filters[key].map((v, vidx) => '$' + idx++).join(',')
85
- sql = key + ' IN (' + sql + ')'
187
+ let sql = filters[key].map(() => getPlaceholder(idx++)).join(',')
188
+ sql &&= '"' + key + '" IN (' + sql + ')'
86
189
  parameters = parameters.concat(filters[key])
87
190
  return sql
88
191
  }
89
- const sql = key + ' = $' + idx++
192
+ // const sql = '"' + key + '" = $' + idx++;
193
+ const sql = '"' + key + '" = ' + getPlaceholder(idx++)
90
194
  parameters.push(filters[key])
91
195
  return sql
92
196
  })
197
+ .filter((v) => v)
93
198
  .join(' AND ')
94
199
  where &&= `WHERE ${where}`
95
200
 
96
201
  return { select, insert, update, where, parameters }
97
202
  }
203
+
204
+ export const __table = async (sql) => {
205
+ await options.query(sql)
206
+ }
207
+
208
+ export const __clear = async (table) => {
209
+ if (options.log) {
210
+ options.log('__clear', { table })
211
+ }
212
+ options.query(`DELETE FROM ${table}`)
213
+ }
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@1auth/store-sql",
3
- "version": "0.0.0-alpha.6",
3
+ "version": "0.0.0-alpha.60",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "engines": {
7
- "node": ">=16"
7
+ "node": ">=20"
8
8
  },
9
9
  "engineStrict": true,
10
10
  "publishConfig": {
@@ -27,7 +27,7 @@
27
27
  ],
28
28
  "scripts": {
29
29
  "test": "npm run test:unit",
30
- "test:unit": "ava"
30
+ "test:unit": "node --test"
31
31
  },
32
32
  "license": "MIT",
33
33
  "funding": {
@@ -48,10 +48,13 @@
48
48
  "url": "https://github.com/willfarrell/1auth/issues"
49
49
  },
50
50
  "homepage": "https://github.com/willfarrell/1auth",
51
- "gitHead": "be4a52c6e52443e7b21d0f67cb6062ae9f6f069c",
51
+ "gitHead": "7a6c0fbb8ab71d6a2171e678697de9f237568431",
52
52
  "peerDependencies": {
53
53
  "@aws-sdk/client-dynamodb": "^3.0.0",
54
54
  "@aws-sdk/util-dynamodb": "^3.0.0",
55
- "uuid": "9.0.0"
55
+ "uuid": "^11.0.0"
56
+ },
57
+ "devDependencies": {
58
+ "better-sqlite3": "^11.0.0"
56
59
  }
57
60
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2023 will Farrell
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.