<commit_before>
'use strict';

/*
* Module dependencies.
*/
const moment = require('moment');
const is = require('is');
const arrify = require('arrify');
const extend = require('extend');
const hooks = require('promised-hooks');
const ds = require('@google-cloud/datastore')();
const validator = require('validator');

const Entity = require('./entity');
const datastoreSerializer = require('./serializer').Datastore;
const utils = require('./utils');
const queryHelpers = require('./helper').QueryHelpers;
const GstoreError = require('./error.js');

class Model extends Entity {
    static compile(kind, schema, gstore) {
        const ModelInstance = class extends Model {};
        hooks.wrap(ModelInstance);

        ModelInstance.schema = schema;
        ModelInstance.registerHooksFromSchema();

        /**
         * Add schema "custom" methods on the prototype
         * to be accesible from Entity instances
         */
        applyMethods(ModelInstance.prototype, schema);
        applyStatics(ModelInstance, schema);

        ModelInstance.prototype.entityKind = ModelInstance.entityKind = kind;
        ModelInstance.prototype.gstore = ModelInstance.gstore = gstore;

        /**
         * Create virtual properties (getters and setters for entityData object)
         */
        Object.keys(schema.paths)
            .filter(key => ({}.hasOwnProperty.call(schema.paths, key)))
            .forEach(key => Object.defineProperty(ModelInstance.prototype, key, {
                get: function getProp() { return this.entityData[key]; },
                set: function setProp(newValue) {
                    this.entityData[key] = newValue;
                },
            }));

        return ModelInstance;
    }

    /**
     * Pass all the "pre" and "post" hooks from schema to
     * the current ModelInstance
     */
    static registerHooksFromSchema() {
        const self = this;
        const callQueue = this.schema.callQueue.model;

        if (!Object.keys(callQueue).length) {
            return this;
        }

        Object.keys(callQueue).forEach(addHooks);

        return self;

        // --------------------------------------

        function addHooks(method) {
            // Add Pre hooks
            callQueue[method].pres.forEach((fn) => {
                self.pre(method, fn);
            });

            // Add Post hooks
            callQueue[method].post.forEach((fn) => {
                self.post(method, fn);
            });
        }
    }

    /**
     * Get and entity from the Datastore
     */
    static get(id, ancestors, namespace, transaction, options, cb) {
        const _this = this;
        const args = Array.prototype.slice.apply(arguments);
        const multiple = is.array(id);

        cb = args.pop();
        id = parseId(id);
        ancestors = args.length > 1 ? args[1] : undefined;
        namespace = args.length > 2 ? args[2] : undefined;
        transaction = args.length > 3 ? args[3] : undefined;
        options = args.length > 4 ? args[4] : {};

        const key = this.key(id, ancestors, namespace);

        if (transaction) {
            if (transaction.constructor.name !== 'Transaction') {
                throw Error('Transaction needs to be a gcloud Transaction');
            }
            return transaction.get(key)
                                .then(onEntity, onError);
        }

        return this.gstore.ds.get(key)
                                .then(onEntity, onError);

        // -----------------------------------------------------

        function onEntity(data) {
            if (data.length === 0) {
                return cb({
                    code: 404,
                    message: `${_this.entityKind} { ${id.toString()} } not found`,
                });
            }

            let entity = data[0];

            if (!multiple) {
                entity = [entity];
            }

            entity = entity.map(e => _this.__model(e, null, null, null, e[_this.gstore.ds.KEY]));

            if (multiple && options.preserveOrder) {
                entity.sort((a, b) => id.indexOf(a.entityKey.id) - id.indexOf(b.entityKey.id));
            }

            const response = multiple ? entity : entity[0];
            return cb(null, response);
        }

        function onError(err) {
            return cb(err);
        }
    }<commit_msg>fixes UnhandledPromiseRejectionWarning when non-existing key is given<commit_after>
'use strict';

/*
* Module dependencies.
*/
const moment = require('moment');
const is = require('is');
const arrify = require('arrify');
const extend = require('extend');
const hooks = require('promised-hooks');
const ds = require('@google-cloud/datastore')();
const validator = require('validator');

const Entity = require('./entity');
const datastoreSerializer = require('./serializer').Datastore;
const utils = require('./utils');
const queryHelpers = require('./helper').QueryHelpers;
const GstoreError = require('./error.js');

class Model extends Entity {
    static compile(kind, schema, gstore) {
        const ModelInstance = class extends Model {};
        hooks.wrap(ModelInstance);

        ModelInstance.schema = schema;
        ModelInstance.registerHooksFromSchema();

        /**
         * Add schema "custom" methods on the prototype
         * to be accesible from Entity instances
         */
        applyMethods(ModelInstance.prototype, schema);
        applyStatics(ModelInstance, schema);

        ModelInstance.prototype.entityKind = ModelInstance.entityKind = kind;
        ModelInstance.prototype.gstore = ModelInstance.gstore = gstore;

        /**
         * Create virtual properties (getters and setters for entityData object)
         */
        Object.keys(schema.paths)
            .filter(key => ({}.hasOwnProperty.call(schema.paths, key)))
            .forEach(key => Object.defineProperty(ModelInstance.prototype, key, {
                get: function getProp() { return this.entityData[key]; },
                set: function setProp(newValue) {
                    this.entityData[key] = newValue;
                },
            }));

        return ModelInstance;
    }

    /**
     * Pass all the "pre" and "post" hooks from schema to
     * the current ModelInstance
     */
    static registerHooksFromSchema() {
        const self = this;
        const callQueue = this.schema.callQueue.model;

        if (!Object.keys(callQueue).length) {
            return this;
        }

        Object.keys(callQueue).forEach(addHooks);

        return self;

        // --------------------------------------

        function addHooks(method) {
            // Add Pre hooks
            callQueue[method].pres.forEach((fn) => {
                self.pre(method, fn);
            });

            // Add Post hooks
            callQueue[method].post.forEach((fn) => {
                self.post(method, fn);
            });
        }
    }

    /**
     * Get and entity from the Datastore
     */
    static get(id, ancestors, namespace, transaction, options, cb) {
        const _this = this;
        const args = Array.prototype.slice.apply(arguments);
        const multiple = is.array(id);

        cb = args.pop();
        id = parseId(id);
        ancestors = args.length > 1 ? args[1] : undefined;
        namespace = args.length > 2 ? args[2] : undefined;
        transaction = args.length > 3 ? args[3] : undefined;
        options = args.length > 4 ? args[4] : {};

        const key = this.key(id, ancestors, namespace);

        if (transaction) {
            if (transaction.constructor.name !== 'Transaction') {
                throw Error('Transaction needs to be a gcloud Transaction');
            }
            return transaction.get(key)
                                .then(onEntity, onError);
        }

        return this.gstore.ds.get(key)
                                .then(onEntity, onError);

        // -----------------------------------------------------

        function onEntity(data) {
            if (data.length === 0 || typeof data[0] === 'undefined') {
                return cb({
                    code: 404,
                    message: `${_this.entityKind} { ${id.toString()} } not found`,
                });
            }

            let entity = data[0];

            if (!multiple) {
                entity = [entity];
            }

            entity = entity.map(e => _this.__model(e, null, null, null, e[_this.gstore.ds.KEY]));

            if (multiple && options.preserveOrder) {
                entity.sort((a, b) => id.indexOf(a.entityKey.id) - id.indexOf(b.entityKey.id));
            }

            const response = multiple ? entity : entity[0];
            return cb(null, response);
        }

        function onError(err) {
            return cb(err);
        }
    }
{'fraction_non_alphanumeric': 0.14295439074200136, 'fraction_numerical': 0.0032902201043793966, 'mean_word_length': 1.7452507007162879, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4063543', 'n_tokens_mistral': 2313, 'n_tokens_neox': 2237, 'n_words': 547}