{"id":15013455,"url":"https://github.com/voodooattack/file-scalar","last_synced_at":"2025-04-12T04:43:51.066Z","repository":{"id":135563519,"uuid":"106062632","full_name":"voodooattack/file-scalar","owner":"voodooattack","description":"A `File` scalar for Vulcan.js to facilitate file uploads with GraphQL.","archived":false,"fork":false,"pushed_at":"2017-10-14T18:54:18.000Z","size":12,"stargazers_count":8,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-06T15:55:38.446Z","etag":null,"topics":["file-upload","file-uploader","fileupload","fileuploder","graphql","meteor","meteor-package","meteorjs","vulcanjs"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/voodooattack.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-10-07T01:10:33.000Z","updated_at":"2019-11-18T01:52:28.000Z","dependencies_parsed_at":"2024-06-06T21:34:50.731Z","dependency_job_id":null,"html_url":"https://github.com/voodooattack/file-scalar","commit_stats":{"total_commits":4,"total_committers":1,"mean_commits":4.0,"dds":0.0,"last_synced_commit":"076c83a1fad0e96af63dd9b4518bf1e694f45c96"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/voodooattack%2Ffile-scalar","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/voodooattack%2Ffile-scalar/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/voodooattack%2Ffile-scalar/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/voodooattack%2Ffile-scalar/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/voodooattack","download_url":"https://codeload.github.com/voodooattack/file-scalar/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248519465,"owners_count":21117757,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["file-upload","file-uploader","fileupload","fileuploder","graphql","meteor","meteor-package","meteorjs","vulcanjs"],"created_at":"2024-09-24T19:44:18.350Z","updated_at":"2025-04-12T04:43:51.028Z","avatar_url":"https://github.com/voodooattack.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# file-scalar\n\nThis package provides a `File` scalar data-type for your GraphQL schema. You can simply pass a browser `File` object as an argument to your mutations and the package takes care of the rest.\n\nYour resolvers will receive a `Stream.Readable`, which they can then store or manipulate to their liking.\n\nIn addition, the stream passed to your resolvers will have these additional properties:\n\n| Type   | Property         | Description                                  |\n|--------|------------------|----------------------------------------------|\n| string | filename         | The name of the file on the user's computer. |\n| string | transferEncoding | The encoding used to transfer the file.      |\n| string | mimeType         | The mime-type of the file. e.g. `image/png`  |\n| string | fieldname        | The name of the field in the request.        |\n\n## Fully functional example (with bonus image resizing)\n\nIn images/collection.js:\n\n\u003e Here we're using [Meteor-CollectionFS](https://github.com/CollectionFS/Meteor-CollectionFS) for file uploads and `cfs:graphicsmagick` to manipulate images.\n\n```js\n\nimport * as path from 'path';\nimport { getSetting, GraphQLSchema } from 'meteor/vulcan:lib';\nimport DataLoader from 'dataloader';\n\nfunction createThumbnail(fileObj, readStream, writeStream) {\n  // Transform the image into a 64x64px thumbnail\n  gm(readStream, fileObj.name()).resize('64', '64').stream().pipe(writeStream);\n}\n\nexport const DEFAULT_UPLOADS_PATH = '~/uploads';\n\nexport const Images = new FS.Collection(\"images\", {\n  stores: [\n    new FS.Store.FileSystem(\"original\", {\n      path: path.join(getSetting('uploadsPath', DEFAULT_UPLOADS_PATH), 'original')\n    }),\n    new FS.Store.FileSystem(\"thumb\", {\n      path: path.join(getSetting('uploadsPath', DEFAULT_UPLOADS_PATH), 'thumbs'),\n      transformWrite: createThumbnail\n    })\n  ],\n  filter: {\n    allow: {\n       contentTypes: ['image/*'] //allow only images in this FS.Collection\n    }\n  }\n});\n\nImages.loader = new DataLoader(async function (ids) {\n  const documents = Images.find({ _id: { $in: ids } }).fetch();\n  return ids.map(id =\u003e documents.find(doc =\u003e doc._id === id));\n});\n\nGraphQLSchema.addToContext({ Images });\n\n```\n\nIn posts/schema.js:\n\n```js\nimport { getComponent } from 'meteor/vulcan:lib';\nimport { Images } from '../images/collection';\nimport { Readable } from 'stream';\nimport SimpleSchema from 'simpl-schema';\n\nfunction createInsertHandler(attribute, Collection) {\n  return function (document, currentUser) {\n    if (document[attribute] instanceof Readable) {\n      const file = new FS.File();\n      file.attachData(document[attribute], { type: document[attribute].mimeType });\n      file.owner = currentUser._id;\n      file.name(document[attribute].filename);\n      file.type(document[attribute].mimeType);\n      const { _id } = Collection.insert(file);\n      return _id;\n    }\n    return document[attribute];\n  }\n}\n\nfunction createEditHandler(attribute, Collection) {\n  return function (modifiers, document, currentUser) {\n    if (modifiers[ '$set' ] \u0026\u0026 modifiers[ '$set' ][ attribute ]) {\n      const streamOrId = modifiers[ '$set' ][ attribute ];\n      if (streamOrId instanceof Readable) {\n        const file = new FS.File();\n        file.attachData(streamOrId, { type: streamOrId.mimeType });\n        file.owner = currentUser._id;\n        file.name(streamOrId.filename);\n        file.type(streamOrId.mimeType);\n        const { _id } = Collection.insert(file);\n        return _id;\n      }\n      return streamOrId;\n    }\n  }\n}\n\nconst schema = {\n\n  // ... default properties ...\n  \n  /**\n  * This field will accept a file upload in mutations (new, edit) and resolve to an image \n  * URL in queries. Pretty neat, huh?  \n  */\n  featuredImage: {\n    label: 'Featured Image',\n    type: SimpleSchema.oneOf({ type: Object, blackbox: true }, String), /** IMPORTANT: SimpleSchema will coerce the type if we set it to `String`, so we have to add `Object` here. */\n    viewableBy: ['guests'],\n    insertableBy: ['members'],\n    editableBy: ['members'],\n    control: getComponent('Upload'), /** use the Upload form component (Provided by file-scalar) */\n    /**\n    * Here we save the file and return an ID in the Images collection.  \n    */\n    onInsert: createInsertHandler('featuredImage', Images),\n    onEdit: createEditHandler('featuredImage', Images),\n    /**\n    * Resolve this field as a URL instead of an image ID. \n    * The URL will be accessible from the browser.\n    */\n    resolveAs: {\n      fieldName: 'featuredImage',\n      type: 'String',\n      arguments: `\n        # Image sizes allowed: 'original', 'thumb'\n        size: String\n      `,\n      async resolver(document, args, context) {\n        if (args.size \u0026\u0026 ['original', 'thumb'].indexOf(args.size) === -1)\n                throw new Error('Invalid image size specified.');          \n        const image = await context.Images.loader.load(document.featuredImage);\n        if (image)\n          return image.url({ store: args.size || 'original' });\n      }\n    }\n  }\n  // ...\n}\n```\n\n## See also:\n\n- [internal-graphql](https://gist.github.com/voodooattack/c4f7a261ea189ffb1894e9cb5e018587): Eliminate server-side fetches in Vulcan.js.\n- [webtoken-session](https://gist.github.com/voodooattack/7a02881b0c762630160424f742b6f780): A server-side persistent session API for Vulcan.js.\n\n## License\n\nCopyright 2017, Abdullah Ali\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvoodooattack%2Ffile-scalar","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvoodooattack%2Ffile-scalar","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvoodooattack%2Ffile-scalar/lists"}