forked from InfraWay/post-medium-action
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (77 loc) · 2.15 KB
/
index.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
82
83
84
85
const fs = require('fs');
const sdk = require('@redcode/medium-sdk');
const md = require('meta-marked');
const {
INPUT_ACCESS_TOKEN,
INPUT_MARKDOWN_FILE,
INPUT_BASE_URL,
INPUT_POST_URL,
INPUT_POST_STATUS = sdk.PostPublishStatus.DRAFT,
INPUT_POST_LICENSE = sdk.PostLicense.ALL_RIGHTS_RESERVED,
} = process.env;
const client = new sdk.MediumClient();
client.setAccessToken(INPUT_ACCESS_TOKEN);
const getUser = async () => {
return new Promise((resolve, reject) => {
client.getUser((err, user) => {
if (err) {
reject(err);
return;
}
resolve(user);
});
});
};
const createPost = async (userId, postUrl, title, tags, markdown) => {
return new Promise((resolve, reject) => {
client.createPost({
userId,
title: title,
tags: tags,
canonicalUrl: postUrl,
publishStatus: INPUT_POST_STATUS,
license: INPUT_POST_LICENSE,
contentFormat: sdk.PostContentFormat.MARKDOWN,
content: markdown,
}, (err, post) => {
if (err) {
reject(err);
return;
}
resolve(post);
});
});
};
const getFileContents = async (filepath) => {
return new Promise((resolve, reject) => {
fs.readFile(filepath, 'utf8', (err, data) => {
if (err) {
return reject(err);
}
resolve(data);
});
});
};
const replaceLocalLinks = (content) => {
if (!INPUT_BASE_URL) {
return content;
}
return content.replace(/\]\((\/[^\)]+)\)/gi, `](${INPUT_BASE_URL}$1)`)
};
(async () => {
try {
const data = await getFileContents(INPUT_MARKDOWN_FILE);
const { id } = await getUser();
const { meta, markdown } = md(replaceLocalLinks(data));
const { title, tags = [], slug } = meta || {};
const postBaseUrl = INPUT_POST_URL || INPUT_BASE_URL || '';
const postUrl = postBaseUrl ? [postBaseUrl.replace(/\/+$/, ''), slug].join('/') : undefined;
const post = await createPost(id, postUrl, title, tags, markdown);
console.log(`::set-output name=id::${post.id}`);
console.log(`::set-output name=url::${post.url}`);
process.exit(0);
} catch (err) {
console.log(`::error ::${err.message}`);
process.exit(1);
}
})();