1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | "use strict";
|
15 |
|
16 | var fluid = fluid || require("infusion"),
|
17 | kettle = fluid.registerNamespace("kettle"),
|
18 | fs = require("fs");
|
19 |
|
20 | fluid.require("querystring", require, "node.querystring");
|
21 |
|
22 | fluid.registerNamespace("kettle.dataSource");
|
23 |
|
24 |
|
25 |
|
26 | fluid.defaults("kettle.dataSource.file", {
|
27 | gradeNames: ["kettle.dataSource"],
|
28 | readOnlyGrade: "kettle.dataSource.file",
|
29 | invokers: {
|
30 | getImpl: {
|
31 | funcName: "kettle.dataSource.file.handle",
|
32 | args: ["{that}", "{arguments}.0", "{arguments}.1"]
|
33 | }
|
34 | }
|
35 | });
|
36 |
|
37 | fluid.defaults("kettle.dataSource.file.writable", {
|
38 | gradeNames: ["kettle.dataSource.writable"],
|
39 | invokers: {
|
40 | setImpl: {
|
41 | funcName: "kettle.dataSource.file.handle",
|
42 | args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"]
|
43 | }
|
44 | }
|
45 | });
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 | kettle.dataSource.file.handle = function (that, requestOptions, directModel, model) {
|
58 | if (!that.options.path) {
|
59 | fluid.fail("Cannot operate file dataSource ", that, " without an option named \"path\"");
|
60 | }
|
61 | var fileName = kettle.dataSource.URL.resolveUrl(that.options.path, that.options.termMap, directModel, true);
|
62 | var promise = fluid.promise(),
|
63 | method = "readFile",
|
64 | operation = requestOptions.operation,
|
65 | fsCallback = function (error, readData) {
|
66 |
|
67 | if (error) {
|
68 | promise.reject({
|
69 | message: error.message
|
70 | });
|
71 | } else {
|
72 | promise.resolve(requestOptions.operation === "set" ? undefined : readData);
|
73 | }
|
74 | },
|
75 | args = [fileName, that.options.charEncoding];
|
76 | promise.accumulateRejectionReason = function (originError) {
|
77 | return kettle.upgradeError(originError, " while " + (operation === "set" ? "writing" : "reading") + " file " + fileName);
|
78 | };
|
79 | if (operation === "set") {
|
80 | method = "writeFile";
|
81 | args.splice(1, 0, model);
|
82 | } else {
|
83 | if (!fs.existsSync(fileName)) {
|
84 | if (requestOptions.notFoundIsEmpty) {
|
85 | promise.resolve(undefined);
|
86 | } else {
|
87 | promise.reject({
|
88 | isError: true,
|
89 | message: "File " + fileName + " was not found",
|
90 | statusCode: 404
|
91 | });
|
92 | }
|
93 | return promise;
|
94 | }
|
95 | }
|
96 | args.push(kettle.wrapCallback(fsCallback));
|
97 | fs[method].apply(null, args);
|
98 | return promise;
|
99 | };
|
100 |
|
101 |
|
102 |
|
103 | fluid.defaults("kettle.dataSource.file.moduleTerms", {
|
104 | gradeNames: "kettle.dataSource.file",
|
105 | termMap: "@expand:fluid.module.terms()"
|
106 | });
|