Created
April 30, 2020 22:01
-
-
Save ademilter/3ddc6dd7e6fdba7d38e4cc33810c4fd8 to your computer and use it in GitHub Desktop.
github create md file with next api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import moment from 'moment' | |
import axios from 'axios' | |
import slug from 'slug' | |
import metadata from 'url-metadata' | |
import { string } from 'yup' | |
const schemaToken = string().matches(/(Bearer)/) | |
const schemaUrl = string().required().url() | |
import { baseURL, cleanUrl } from '../../utils/helper' | |
export default async (req, res) => { | |
// HAS TOKEN | |
const { authorization } = req.headers | |
const isValidToken = await schemaToken.isValid(authorization) | |
if (!isValidToken) { | |
return await res.status(400).end(JSON.stringify({ message: 'token error' })) | |
} | |
// HAS URL | |
const { url } = req.body | |
const isValidUrl = await schemaUrl.isValid(url) | |
if (!isValidUrl) { | |
return await res.status(400).end(JSON.stringify({ message: 'url error' })) | |
} | |
// CONTENT | |
const { title, description } = await metadata(url) | |
const fileName = slug(cleanUrl(url), { | |
lower: true | |
}) | |
const CONTENT = `--- | |
title: "${title}" | |
description: "${description}" | |
url: "${url}" | |
date: ${moment().format('YYYY-MM-DD')} | |
--- | |
` | |
try { | |
await axios.put( | |
`${baseURL}/src/data/links/${fileName}.md`, | |
{ | |
message: `new link: "${fileName}"`, | |
content: Buffer.from(CONTENT).toString('base64') | |
}, | |
{ headers: { authorization } } | |
) | |
console.log('created') | |
res.status(200).end(JSON.stringify({ message: 'created' })) | |
} catch (e) { | |
console.log(e) | |
res.status(400).end(JSON.stringify({ message: 'ups!!' })) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment