<commit_before>import 'package:http/http.dart' show Response, Request;
import 'package:http/browser_client.dart';
import 'dart:async';
import 'dart:convert';
import 'http_status_codes.dart';
import 'dart:math' as math;
import 'utils.dart';

class HttpClientInMemoryBackendService extends BrowserClient {

  InMemoryBackendConfigArgs _config;
  Map<String,dynamic> _db = {};
  CreateDb _seedData;

  HttpClientInMemoryBackendService(CreateDb seedData,{InMemoryBackendConfigArgs config}){
    _seedData = seedData;
    _resetDb();
    final location = new Location('./');
    _config = new InMemoryBackendConfig(
        delay: config?.delay,
        delete404: config?.delete404,
        host: location.host,
        rootPath: location.pathname
    );
  }

  Future<Response> get(dynamic url, {Map<String, String> headers}) async
    => _handleRequest(_createRequest('GET',url,headers));

  Future<Response> post(dynamic url, {Map<String, String> headers,
      dynamic body, Encoding encoding}) async
    => _handleRequest(_createRequest('POST',url,headers,body,encoding));

  Request _createRequest(String method, url,
      Map<String, String> headers, [body, Encoding encoding]) {

    if (url is String) url = Uri.parse(url);
    var request = new Request(method, url);

    if (headers != null) request.headers.addAll(headers);
    if (encoding != null) request.encoding = encoding;
    if (body != null) {
      if (body is String) {
        request.body = body;
      } else if (body is List) {
        request.bodyBytes = body;
      } else if (body is Map) {
        request.bodyFields = body;
      } else {
        throw new ArgumentError('Invalid request body "$body".');
      }
    }

    return request;
  }

  Response _handleRequest(Request req) {
    final data = _parseUrl(req.url.toString());

    final reqInfo = new RequestInfo(
        req,
        data.base,
        new Collection(data.collectionName, this._db[data.collectionName]),
        {'Content-Type':'application/json'},
        _parseId(data.id),
        data.resourceUrl
    );

    Response response;

    switch(req.method.toLowerCase()) {
      case 'get':
        response = _get(reqInfo);
        break;
      case 'post':
        response = _post(reqInfo);
        break;
      case 'put':
        response = _put(reqInfo);
        break;
      case 'delete':
        response = _delete(reqInfo);
        break;
    }

    return response;
  }

  Response _get(RequestInfo req){
    final data = req.hasId ? _findById(req.collection, req.id) : req.collection.data;
    if(data == null){
      return _createErrorResponse(
          STATUS['NOT_FOUND'],
          '"${req.collection.name}" with id="${req.id}" not found');
    }
    final body = JSON.encode({'data':data});
    return new Response(body, STATUS['OK'], headers: req.headers);
  }

  Response _post(RequestInfo reqInfo){
    Map item = JSON.decode(reqInfo.req.body);
    if(!item.containsKey('id')){
      item['id'] = reqInfo.id ?? _genId(reqInfo.collection);
    }
    // ignore the request id, if any. Alternatively,
    // could reject request if id differs from item.id<commit_msg>add delay to response<commit_after>import 'package:http/http.dart' show Response, Request;
import 'package:http/browser_client.dart';
import 'dart:async';
import 'dart:convert';
import 'http_status_codes.dart';
import 'dart:math' as math;
import 'utils.dart';

class HttpClientInMemoryBackendService extends BrowserClient {

  InMemoryBackendConfigArgs _config;
  Map<String,dynamic> _db = {};
  CreateDb _seedData;

  HttpClientInMemoryBackendService(CreateDb seedData,{InMemoryBackendConfigArgs config}){
    _seedData = seedData;
    _resetDb();
    final location = new Location('./');
    _config = new InMemoryBackendConfig(
        delay: config?.delay,
        delete404: config?.delete404,
        host: location.host,
        rootPath: location.pathname
    );
  }

  Future<Response> get(dynamic url, {Map<String, String> headers})
    => _handleRequest(_createRequest('GET',url,headers));

  Future<Response> post(dynamic url, {Map<String, String> headers,
      dynamic body, Encoding encoding}) async
    => _handleRequest(_createRequest('POST',url,headers,body,encoding));

  Request _createRequest(String method, url,
      Map<String, String> headers, [body, Encoding encoding]) {

    if (url is String) url = Uri.parse(url);
    var request = new Request(method, url);

    if (headers != null) request.headers.addAll(headers);
    if (encoding != null) request.encoding = encoding;
    if (body != null) {
      if (body is String) {
        request.body = body;
      } else if (body is List) {
        request.bodyBytes = body;
      } else if (body is Map) {
        request.bodyFields = body;
      } else {
        throw new ArgumentError('Invalid request body "$body".');
      }
    }

    return request;
  }

  Future<Response> _handleRequest(Request req) async {
    final data = _parseUrl(req.url.toString());

    final reqInfo = new RequestInfo(
        req,
        data.base,
        new Collection(data.collectionName, this._db[data.collectionName]),
        {'Content-Type':'application/json'},
        _parseId(data.id),
        data.resourceUrl
    );

    Response response;

    switch(req.method.toLowerCase()) {
      case 'get':
        response = _get(reqInfo);
        break;
      case 'post':
        response = _post(reqInfo);
        break;
      case 'put':
        response = _put(reqInfo);
        break;
      case 'delete':
        response = _delete(reqInfo);
        break;
    }

    final duration = new Duration(milliseconds: _config.delay);
    return await new Future.delayed(duration,() => response);
  }

  Response _get(RequestInfo req){
    final data = req.hasId ? _findById(req.collection, req.id) : req.collection.data;
    if(data == null){
      return _createErrorResponse(
          STATUS['NOT_FOUND'],
          '"${req.collection.name}" with id="${req.id}" not found');
    }
    final body = JSON.encode({'data':data});
    return new Response(body, STATUS['OK'], headers: req.headers);
  }

  Response _post(RequestInfo reqInfo){
    Map item = JSON.decode(reqInfo.req.body);
    if(!item.containsKey('id')){
      item['id'] = reqInfo.id ?? _genId(reqInfo.collection);
    }
    // ignore the request id, if any. Alternatively,
    // could reject request if id differs from item.id
{'fraction_non_alphanumeric': 0.12779253241680988, 'fraction_numerical': 0.0018747070770192159, 'mean_word_length': 3.0621827411167515, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 21, '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': '6068211', 'n_tokens_mistral': 1917, 'n_tokens_neox': 1879, 'n_words': 466}