Read all JPG images in a directory, convert them to JSON and Post them to a Graphql Endpoint

Github Repo

1. Read all files in a Directory


  const files = [];
  fs.readdirSync(dir).forEach((filename) => {
    const name = path.parse(filename).name;
    const ext = path.parse(filename).ext;
    const filepath = path.resolve(dir, filename);
    const stat = fs.statSync(filepath);
    const isFile = stat.isFile();
  });

2. Convert the JPG to Base64 encoded String

      const base64String = fs.readFileSync(filepath, 'base64');
      files.push({ filepath, name, ext, stat, base64String: `data:image/jpg;base64,${base64String}` });

3. Post to a Graphql endpoint with Axios

const ADD_SKILL = gql`
mutation uploadFileItem($member: String, $title: String!, $image: String!) {
    uploadFileItem(
        data: { member: $member, entityType: Blog, title: $title, type: PHOTO, base64String: $image }
    ) {
        id
        size
        url
        title
        type
    }
}
`

axios.interceptors.request.use(config => {
  const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..JWT';
  config.headers["Authorization"] = `Bearer ${token}`;
  return config;
});

for (let photo of files) {
  const { name, base64String } = photo;
  console.log({ name, base64String })
  axios.post('http://localhost:5000/graphql', {
    query: print(ADD_SKILL),
    variables: {
      member: 'cl4yg6cw90456txjxl2j95vlf',
      title: name,
      image: base64String,
    },
  })
  .then(res => console.log(res))
  .catch(err => console.log(err.response.data))

}