Skip to content

Instantly share code, notes, and snippets.

@tarot
Forked from yusuke8609/package.json
Last active August 29, 2015 14:12
Show Gist options
  • Save tarot/646cba698d3182d38a7d to your computer and use it in GitHub Desktop.
Save tarot/646cba698d3182d38a7d to your computer and use it in GitHub Desktop.
{
"name": "retrieve_folders",
"dependencies": {
"bluebird": "^2.4.2",
"dotenv": "^0.4.0",
"jsforce": "^1.3.1",
"underscore": "^1.7.0",
"unzip": "^0.1.11"
}
}
jsforce = require 'jsforce'
Promise = require 'bluebird'
unzip = require 'unzip'
_ = require 'underscore'
require('dotenv').load()
username = process.env.SALESFORCE_USERNAME
password = process.env.SALESFORCE_PASSWORD
host = process.env.SALESFORCE_HOST || 'login.salesforce.com'
host = "https://#{host}" unless host.match /^https:\/\//
_.mixin
# listMetadataは3つまでしか対象を指定できないので
split: (array, each_size) ->
for i in [0...array.length] by each_size
array.slice(i, i + each_size)
# listMetadataの結果が1件だと配列にならないので
wrap_array: (x) ->
return [] unless x?
if @isArray x then x else [x]
map_values: (obj, iteratee, context) ->
iteratee = @iteratee iteratee, context
@object @map obj, (v, k, o) -> [k, iteratee(v, k, o)]
# 3つずつ取得したlistMetadataを統合する
_.extend require('jsforce/lib/api/metadata').prototype,
list_all: (queries, version) ->
queries = [] unless _.isArray queries
metadata = @
Promise.reduce _.split(queries, 3), (all, queries) ->
metadata.list(queries, version).then (res) -> all.concat _.wrap_array(res)
, []
class Manifest
# 各フォルダタイプのMetadata名と、フォルダ内のファイルのMetadata名
@type_of_folder:
DocumentFolder: 'Document'
DashboardFolder: 'Dashboard'
EmailFolder: 'EmailTemplate'
ReportFolder: 'Report'
parse_list_metadata_result: (list_metadata_result) ->
types = _.chain list_metadata_result
.wrap_array()
.groupBy (e) -> Manifest.type_of_folder[e.type] ? e.type
.map_values (vs) -> vs.map (e) -> e.fullName
.value()
_.extend @, types
to_unpackaged_request: (version = '32.0') ->
unpackaged:
version: version
types: _.map @, (v, k) -> name: k, members: v
connection = new jsforce.Connection loginUrl: host
connection.login(username, password)
.then ->
connection.version = '32.0'
.then ->
# フォルダタイプ毎のlistMetadata
queries = _.keys(Manifest.type_of_folder).map (e) -> type: e
connection.metadata.list_all queries
.then (folder_metadata) ->
# フォルダ内コンポーネントのlistMetadata
queries = folder_metadata.map (e) -> type: Manifest.type_of_folder[e.type], folder: e.fullName
connection.metadata.list_all queries
.then (component_metadata) -> [folder_metadata, component_metadata]
.then ([folder_metadata, component_metadata]) ->
manifest = new Manifest().parse_list_metadata_result folder_metadata.concat(component_metadata)
connection.metadata.retrieve manifest.to_unpackaged_request()
.stream().pipe unzip.Extract(path: '.')
.fail ->
console.error arguments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment