-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathcreate-file-node.js
81 lines (77 loc) · 2.31 KB
/
create-file-node.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const slash = require(`slash`)
const path = require(`path`)
const fs = require(`fs-extra`)
const mime = require(`mime`)
const prettyBytes = require(`pretty-bytes`)
const md5File = require(`bluebird`).promisify(require(`md5-file`))
const crypto = require(`crypto`)
exports.createFileNode = async (
pathToFile,
createNodeId,
pluginOptions = {}
) => {
const slashed = slash(pathToFile)
const parsedSlashed = path.parse(slashed)
const slashedFile = {
...parsedSlashed,
absolutePath: slashed,
// Useful for limiting graphql query with certain parent directory
relativeDirectory: path.relative(
pluginOptions.path || process.cwd(),
parsedSlashed.dir
),
}
const stats = await fs.stat(slashedFile.absolutePath)
let internal
if (stats.isDirectory()) {
const contentDigest = crypto
.createHash(`md5`)
.update(
JSON.stringify({ stats: stats, absolutePath: slashedFile.absolutePath })
)
.digest(`hex`)
internal = {
contentDigest,
type: `Directory`,
description: `Directory "${path.relative(process.cwd(), slashed)}"`,
}
} else {
const contentDigest = await md5File(slashedFile.absolutePath)
const mediaType = mime.getType(slashedFile.ext)
internal = {
contentDigest,
type: `File`,
mediaType: mediaType ? mediaType : `application/octet-stream`,
description: `File "${path.relative(process.cwd(), slashed)}"`,
}
}
// Stringify date objects.
return JSON.parse(
JSON.stringify({
// Don't actually make the File id the absolute path as otherwise
// people will use the id for that and ids shouldn't be treated as
// useful information.
id: createNodeId(pathToFile),
children: [],
parent: null,
internal,
sourceInstanceName: pluginOptions.name || `__PROGRAMMATIC__`,
absolutePath: slashedFile.absolutePath,
relativePath: slash(
path.relative(
pluginOptions.path || process.cwd(),
slashedFile.absolutePath
)
),
extension: slashedFile.ext.slice(1).toLowerCase(),
size: stats.size,
prettySize: prettyBytes(stats.size),
modifiedTime: stats.mtime,
accessTime: stats.atime,
changeTime: stats.ctime,
birthTime: stats.birthtime,
...slashedFile,
...stats,
})
)
}