Skip to content

Commit b8dbeb0

Browse files
committed
Add file read support
1 parent f10c235 commit b8dbeb0

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

lib/index.js

+24-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os from 'os'
2+
import fs from 'fs'
23
import crypto from 'crypto'
34
import Url from 'url'
45
import Connection from './connection.js'
@@ -35,6 +36,7 @@ export default function Postgres(url, options) {
3536
, queries = Queue()
3637
, listeners = {}
3738
, typeArrayMap = {}
39+
, files = {}
3840

3941
function postgres(xs, ...args) {
4042
return query({}, getConnection(), xs, args)
@@ -142,7 +144,6 @@ export default function Postgres(url, options) {
142144
const promise = new Promise((resolve, reject) => {
143145
query.resolve = resolve
144146
query.reject = reject
145-
146147
ended !== null
147148
? reject(errors.connection('ENDED', options))
148149
: ready
@@ -266,9 +267,10 @@ export default function Postgres(url, options) {
266267
notify,
267268
unsafe,
268269
array,
270+
file,
271+
json,
269272
rows,
270-
row,
271-
json
273+
row
272274
})
273275

274276
function notify(channel, payload) {
@@ -283,6 +285,25 @@ export default function Postgres(url, options) {
283285
return query({ raw: true, simple: options.simple }, connection || getConnection(), xs, args)
284286
}
285287

288+
function file(path) {
289+
const file = files[path]
290+
291+
if (typeof file === 'string')
292+
return query({ raw: true, simple: true }, connection || getConnection(), files[path])
293+
294+
const promise = (file || new Promise((resolve, reject) => fs.readFile(path, 'utf8', (err, str) => {
295+
if (err)
296+
return reject(err)
297+
298+
files[path] = str
299+
const q = query({ raw: true, simple: true }, connection || getConnection(), files[path])
300+
promise.stream = q.stream
301+
resolve(q)
302+
})))
303+
304+
return promise
305+
}
306+
286307
options.types && Object.entries(options.types).forEach(([name, type]) => {
287308
if (name in sql)
288309
throw errors.generic({ message: name + ' is a reserved method name', code: 'RESERVED_METHOD_NAME' })

0 commit comments

Comments
 (0)